<template>
  <div class="app-container container-flex">
    <el-card style="width: 250px; margin-right: 15px">
      <el-tree
        :data="optionsObj.EquipmentType"
        default-expand-all
        highlight-current
        @node-click="handleNodeClick"
      ></el-tree>
    </el-card>
    <!--工具栏-->

    <!-- 表单组件 -->
    <el-dialog
      append-to-body
      :close-on-click-modal="false"
      :before-close="crud.cancelCU"
      :visible.sync="crudCU"
      :title="crud.status.title"
      width="700px"
    >
      <el-form ref="form" :model="form" :rules="rules" size="small" label-width="100px">
        <el-tabs v-model="activeName">
          <el-tab-pane label="通用属性" name="通用属性">
            <el-col :span="14">
              <el-form-item label="设备类型" prop="typeId">
                <treeselect
                  v-model="form.typeId"
                  disabled
                  filterable
                  :defaultExpandLevel="3"
                  :options="optionsObj.EquipmentType"
                  :normalizer="normalizer"
                  style="width: 280px"
                  placeholder="选择所属类型"
                />
              </el-form-item>
              <el-form-item label="设备编号" prop="code">
                <el-input
                  v-model="form.code"
                  size="small"
                  class="filter-item"
                  style="width: 280px"
                />
              </el-form-item>
              <el-form-item label="设备名称" prop="name">
                <el-input
                  v-model="form.name"
                  size="small"
                  class="filter-item"
                  style="width: 280px"
                />
              </el-form-item>
              <el-form-item label="所属设备" prop="parentId">
                <el-select
                  v-model="form.parentId"
                  filterable
                  clearable
                  remote
                  :remote-method="equipmentSelectRemoteHandle"
                  :loading="equipmentSelectLoading"
                  size="small"
                  class="filter-item"
                  style="width: 280px"
                >
                  <el-option
                    v-for="item in equipmentOptions"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
              </el-form-item>
              <el-form-item label="所属部门" prop="departmentId">
                <el-cascader
                  v-model="form.departmentId"
                  :options="optionsObj.Department"
                  :props="{ checkStrictly: true, emitPath: false }"
                  filterable
                  clearable
                  size="small"
                  placeholder="请选择所属部门"
                  style="width: 280px"
                  class="filter-item"
                />
              </el-form-item>
              <el-form-item label="所属区域" prop="areaId">
                <el-select
                  v-model="form.areaId"
                  filterable
                  clearable
                  size="small"
                  class="filter-item"
                  style="width: 280px"
                >
                  <el-option
                    v-for="item in optionsObj.Area"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
              </el-form-item>
              <el-form-item label="规格型号" prop="model">
                <el-input
                  v-model="form.model"
                  size="small"
                  class="filter-item"
                  style="width: 280px"
                />
              </el-form-item>
              <el-form-item label="安装位置" prop="mountingPosition">
                <el-input
                  v-model="form.mountingPosition"
                  size="small"
                  class="filter-item"
                  style="width: 280px"
                />
              </el-form-item>
              <el-form-item label="使用状态" prop="status">
                <el-select
                  v-model="form.status"
                  filterable
                  size="small"
                  class="filter-item"
                  style="width: 280px"
                >
                  <el-option
                    v-for="item in optionsObj.EquipmentStatus"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
              </el-form-item>
              <el-form-item label="备注" prop="remark">
                <el-input v-model="form.remark" type="textarea" autosize style="width: 280px" />
              </el-form-item>
              <el-form-item label="附件" prop="attachment">
                <upload-attachment
                  v-model="form.attachment"
                  :loading.sync="attUploading"
                  :maxSize="1024 * 1024 * 1024"
                  :limit="10"
                />
              </el-form-item>
            </el-col>
            <el-col :span="10">
              <el-form-item label-width="0px" style="margin-top: 10px">
                <upload-picture
                  v-model="form.photoPath"
                  :loading.sync="picUploading"
                  :maxSize="5 * 1024 * 1024"
                />
              </el-form-item>
            </el-col>
          </el-tab-pane>
          <el-tab-pane v-if="form.type.calibrationEnable" label="检定" name="检定">
            <el-form-item  label="检定周期" prop="calibration.calibrationPeriod">
              <el-input
                v-model="form.calibration.calibrationPeriod"
                size="small"
                class="filter-item"
                style="width: 280px"
              />月
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="扩展属性" name="扩展属性">
            <el-form-item
              v-for="(item, index) in form.typeExtensionData"
              :key="item.id"
              :label="item.name"
              :prop="`typeExtensionData[${index}].value`"
              :rules="customComponentRules(item)"
              label-width="130px"
            >
              <custom-component
                v-model="item.value"
                :type="item.componentType"
                :unit="item.unit"
                :isTag="item.isTag"
                :isRequired="item.isRequired"
                :config="item.componentConfig"
                :defaultValue="item.defaultValue"
              />
              <span v-if="item.unit" style="margin-left: 10px">{{ item.unit }}</span>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="弹出窗口数据" name="弹出窗口数据">
            <el-table
              :data="form.extraWindowData"
              style="width: 100%"
              :default-sort="{ prop: 'sort' }"
            >
              <el-table-column prop="name" label="名称" align="center">
                <template slot-scope="scope">
                  <el-form-item
                    label-width="0px"
                    :prop="`extraWindowData[${scope.$index}].name`"
                    :rules="{ required: true, trigger: 'blur' }"
                    style="margin-bottom: 0px"
                  >
                    <el-input
                      v-model="scope.row.name"
                      size="small"
                      class="filter-item"
                      style="width: 100%"
                    />
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column prop="value" label="值" align="center">
                <template slot-scope="scope">
                  <el-form-item
                    label-width="0px"
                    :prop="`extraWindowData[${scope.$index}].value`"
                    :rules="{ required: true, trigger: 'blur' }"
                    style="margin-bottom: 0px"
                  >
                    <tag-select-simple
                      v-if="scope.row.isTag"
                      v-model="scope.row.value"
                      size="small"
                      class="filter-item"
                      style="width: 100%"
                    />
                    <el-input
                      v-else
                      v-model="scope.row.value"
                      size="small"
                      class="filter-item"
                      style="width: 100%"
                    />
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column prop="unit" label="单位" align="center" width="100px">
                <template slot-scope="scope">
                  <el-form-item
                    label-width="0px"
                    :prop="`extraWindowData[${scope.$index}].unit`"
                    style="margin-bottom: 0px"
                  >
                    <el-input
                      v-model="scope.row.unit"
                      size="small"
                      class="filter-item"
                      style="width: 100%"
                    />
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column prop="isTag" label="数据标签" align="center" width="80px">
                <template slot-scope="scope">
                  <el-form-item
                    label-width="0px"
                    :prop="`extraWindowData[${scope.$index}].isTag`"
                    style="margin-bottom: 0px"
                  >
                    <el-switch
                      v-model="scope.row.isTag"
                      active-color="#13ce66"
                      inactive-color="#ff4949"
                      :active-value="true"
                      :inactive-value="false"
                    >
                    </el-switch>
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column prop="sort" label="排序" align="center" width="110px">
                <template slot-scope="scope">
                  <el-form-item
                    label-width="0px"
                    :prop="`extraWindowData[${scope.$index}].sort`"
                    style="margin-bottom: 0px"
                  >
                    <el-input-number
                      v-model.number="scope.row.sort"
                      :min="0"
                      :max="999"
                      controls-position="right"
                      style="width: 100%"
                      @change="handleSortExtraWindowData"
                    />
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column prop="operation" label="删除" align="center" width="60px">
                <template slot-scope="scope">
                  <el-popconfirm
                    title="确定删除此数据吗？"
                    @confirm="handleDelExtraWindowData(scope)"
                  >
                    <el-button size="mini" type="danger" icon="el-icon-delete" slot="reference" />
                  </el-popconfirm>
                </template>
              </el-table-column>
              <template slot="append">
                <el-button
                  size="small"
                  type="primary"
                  icon="el-icon-circle-plus-outline"
                  @click="handleAddExtraWindowData()"
                  style="width: 100%"
                />
              </template>
            </el-table>
          </el-tab-pane>
        </el-tabs>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button type="text" @click="crud.cancelCU"> 取消 </el-button>
        <el-button
          :loading="crud.status.cu === 2 || picUploading || attUploading"
          type="primary"
          @click="crud.submitCU"
        >
          确认
        </el-button>
      </div>
    </el-dialog>
    <el-card style="flex-grow: 1">
      <div class="head-container">
        <div v-if="crud.props.searchToggle">
          <!-- 搜索 -->
          <el-input
            v-model="query.code"
            clearable
            size="small"
            placeholder="输入编号搜索"
            style="width: 200px"
            class="filter-item"
            @keyup.enter.native="crud.toQuery"
          />
          <el-input
            v-model="query.name"
            clearable
            size="small"
            placeholder="输入名称搜索"
            style="width: 200px"
            class="filter-item"
            @keyup.enter.native="crud.toQuery"
          />
          <el-input
            v-model="query.model"
            clearable
            size="small"
            placeholder="输入规格型号搜索"
            style="width: 200px"
            class="filter-item"
            @keyup.enter.native="crud.toQuery"
          />
          <el-select
            v-model="query.status"
            filterable
            clearable
            size="small"
            placeholder="请选择运行状态"
            class="filter-item"
            style="width: 160px"
            @change="crud.toQuery"
          >
            <el-option
              v-for="item in optionsObj.EquipmentStatus"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
          <el-cascader
            v-model="query.departmentId"
            :options="optionsObj.Department"
            :props="{ checkStrictly: true, emitPath: false }"
            filterable
            clearable
            size="small"
            placeholder="请选择所属部门"
            style="width: 160px"
            class="filter-item"
          />
          <el-select
            v-model="query.areaId"
            filterable
            clearable
            size="small"
            placeholder="请输入所属区域"
            class="filter-item"
            style="width: 160px"
            @change="crud.toQuery"
          >
            <el-option
              v-for="item in optionsObj.Area"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
          <rrOperation />
        </div>
        <crudOperation :permission="permission">
          <el-button
            slot="left"
            class="filter-item"
            size="mini"
            type="info"
            icon="el-icon-view"
            @click="handleView(crud.selections[0].id)"
            :disabled="crud.selections.length !== 1"
          >
            查看
          </el-button>
        </crudOperation>
      </div>
      <!--表格渲染-->
      <el-table
        v-loading="crud.loading"
        :data="crud.data"
        row-key="id"
        style="width: 100%"
        :tree-props="{ children: 'children', hasChildren: 'nohasChildren' }"
        @select="crud.selectChange"
        @select-all="crud.selectAllChange"
        @selection-change="crud.selectionChangeHandler"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column
          v-for="item in ledgerTableOptions"
          :key="item.prop"
          :label="item.label"
          :prop="item.prop"
          :width="item.width"
          :align="item.align"
          :fixed="item.fixed"
          :sortable="item.sortable"
        >
        </el-table-column>
        <!--   编辑与删除   -->
        <el-table-column
          v-if="checkPer(['admin', 'equipment:ledger:edit', 'equipment:ledger:del'])"
          label="操作"
          width="170px"
          align="center"
          fixed="right"
        >
          <template slot-scope="scope">
            <div style="display: flex">
              <el-button
                :loading="crud.status.cu === 2"
                size="mini"
                type="info"
                icon="el-icon-view"
                @click="handleView(scope.row.id)"
                style="margin-right: 5px"
              />
              <udOperation :data="scope.row" :permission="permission" />
            </div>
          </template>
        </el-table-column>
      </el-table>
      <!--分页组件-->
      <pagination />
    </el-card>
  </div>
</template>

<script>
import permission from '@/directive/permission'
import crudLedger from '@/api/equipment/ledger'
import { getOptions } from '@/api/equipment/public'
import CRUD, { presenter, header, form, crud } from '@crud/crud'
// import { crudOperation, rrOperation, udOperation, pagination } from '@crud'
import crudComps from '@crud'
import { ledgerTableOptions } from '../tableConfig'
import UploadPicture from '@/components/UploadPicture'
import UploadAttachment from '@/components/UploadAttachment'
import CustomComponent from '@/components/CustomComponent'
import TagSelectSimple from '@/components/TagSelectSimple'
import { initData } from '@/api/data'

// vue-treeselect
import Treeselect from '@riophae/vue-treeselect'
import { LOAD_CHILDREN_OPTIONS } from '@riophae/vue-treeselect'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'

import validate from '@/utils/validate'
import dayjs from 'dayjs'

const defaultForm = {
  id: '',
  code: '',
  name: '',
  typeId: '',
  parentId: '',
  model: '',
  departmentId: '',
  areaId: '',
  areaStr: '',
  mountingPosition: '',
  status: '170001',
  remark: '',
  calibration: {
    calibrationPeriod: '',
    calibrationLastTime: '',
    calibrationLastManufacturer: '',
  },
  type: {
    calibrationEnable: false,
  },
  children: [],
  extraWindowData: [],
  photoPath: null,
  attachment: [],
  typeExtensionData: [],
}

export default {
  name: 'EquipmentLedger',
  directives: { permission },
  mixins: [presenter(), header(), form(defaultForm), crud()],
  components: {
    ...crudComps,
    Treeselect,
    UploadPicture,
    UploadAttachment,
    CustomComponent,
    TagSelectSimple,
  },
  cruds() {
    return CRUD({
      title: '设备台账',
      url: 'equipment/ledger/getList',
      listOrder: [],
      crudMethod: { ...crudLedger },
      optShow: { add: true, edit: true, del: true, reset: true, import: true, export: true },
    })
  },
  computed: {
    crudCU() {
      return this.crud.status.cu > 0
    },
    VUE_APP_BASE_API() {
      return process.env.VUE_APP_BASE_API
    },
  },
  watch: {},
  data() {
    return {
      ledgerTableOptions,
      permission: {
        add: ['admin', 'equipment:ledger:add'],
        edit: ['admin', 'equipment:ledger:edit'],
        del: ['admin', 'equipment:ledger:del'],
      },
      rules: {
        code: [{ required: true, message: '编号不能为空', trigger: 'blur' }],
        name: [{ required: true, message: '名称不能为空', trigger: 'blur' }],
        model: [{ required: true, message: '规格型号不能为空', trigger: 'blur' }],
      },
      generalRules: {
        code: [{ required: true, message: '编号不能为空', trigger: 'blur' }],
        name: [{ required: true, message: '名称不能为空', trigger: 'blur' }],
        model: [{ required: true, message: '规格型号不能为空', trigger: 'blur' }],
      },
      fieldOptions: Array.from({ length: 50 }, (item, index) => index + 1),
      optionsObj: {
        Department: [],
        Area: [],
        EquipmentType: [],
        EquipmentStatus: [],
      },
      currType: 0,
      activeName: '通用属性',
      equipmentOptions: [{ label: '无', value: '0' }],
      equipmentSelectLoading: false,
      picUploading: false,
      attUploading: false,
    }
  },
  created() {
    this.getOptions()
  },
  methods: {
    [CRUD.HOOK.beforeToAdd]() {
      if (!this.currType) {
        this.$message.error('请先选择设备类型')
        return false
      }
      this.form.typeId = this.currType
      initData('equipment/extensionConfig/getList', { typeId: this.form.typeId }).then((res) => {
        if (res.code === 20000) this.form.typeExtensionData = res.data.content
      })
    },
    [CRUD.HOOK.beforeToCU]() {
      this.activeName = '通用属性'
      if (this.form.parentId && this.form.parentId != '0') {
        getOptions('Equipment', { id: this.form.parentId }).then((res) => {
          this.equipmentOptions = res.data.content
        })
      } else {
        this.equipmentOptions = [{ label: '无', value: '0' }]
      }

      if (this.form.attachment) this.attachmentFileList = this.form.attachment
      else this.attachmentFileList = []
    },
    handleNodeClick(data) {
      this.currType = data.value
      this.query.typeId = data.value
      this.crud.toQuery()
    },
    handleView(id) {
      this.$router.push({ path: '/equipment/ledger/view', query: { id: id } })
    },
    normalizer(node) {
      return {
        id: node.value,
        label: node.label,
        children: node.children,
      }
    },
    equipmentSelectRemoteHandle(value) {
      if (value && value.length > 2) {
        this.equipmentSelectLoading = true
        getOptions('Equipment', { id: this.form.id, codeOrName: value })
          .then((res) => {
            this.equipmentOptions = res.data.content
            this.equipmentSelectLoading = false
          })
          .catch((err) => {
            this.equipmentOptions = [{ label: '无', value: '0' }]
            this.equipmentSelectLoading = false
          })
      } else {
        this.equipmentOptions = [{ label: '无', value: '0' }]
        this.equipmentSelectLoading = false
      }
    },
    getOptions() {
      Object.keys(this.optionsObj).forEach(async (key) => {
        try {
          let res = await getOptions(key)
          if (res.code === 20000) this.optionsObj[key] = res.data.content
        } catch (error) {
          console.log(error)
        }
      })
    },
    customComponentRules(item) {
      let rules = []
      if (item.isRequired)
        rules.push({
          required: item.isRequired,
          message: `${item.name}不能为空`,
          trigger: 'blur',
        })
      if (item.rule)
        rules.push({
          validator: (rule, value, callback) => {
            Function(
              '"use strict"; return(function(rule, value, callback, item, validate, dayjs){' +
                item.rule +
                '})'
            )()(rule, value, callback, item, validate, dayjs)
          },
          trigger: 'blur',
        })
      return rules
    },
    handleDelExtraWindowData(scope) {
      this.form.extraWindowData.splice(scope.$index, 1)
    },
    handleAddExtraWindowData() {
      this.form.extraWindowData.push({
        name: '',
        value: '',
        unit: '',
        sort: 999,
        isTag: false,
      })
    },
    handleSortExtraWindowData(currentValue, oldValue) {
      this.form.extraWindowData.sort((a, b) => a.sort - b.sort)
    },
  },
}
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
.container-flex {
  display: flex;
}
</style>