<template>
  <ele-modal
    :visible.sync="visible"
    :title="title"
    width="60vw"
    append-to-body
    @close="cancel"
  >
    <div class="switch" v-if="type == 'detail'">
      <div class="switch_left">
        <ul>
          <li
            v-for="item in tabOptions"
            :key="item.key"
            :class="{ active: activeComp == item.key }"
            @click="activeComp = item.key"
          >
            {{ item.name }}
          </li>
        </ul>
      </div>
    </div>

    <el-form
      ref="form"
      :model="form"
      :rules="rules"
      label-width="100px"
      class="create-form"
      v-if="activeComp === 'main'"
    >
      <headerTitle title="基本信息" style="margin-top: 15px"></headerTitle>

      <el-row :gutter="15">
        <el-col v-bind="styleResponsive ? { lg: 8, md: 12 } : { span: 8 }">
          <el-form-item label="编码:" prop="code">
            <el-input v-model="form.code" disabled />
          </el-form-item>
        </el-col>
        <el-col v-bind="styleResponsive ? { lg: 8, md: 12 } : { span: 8 }">
          <el-form-item label="名称:" prop="name">
            <el-input v-model="form.name" :disabled="type == 'detail'" />
          </el-form-item>
        </el-col>

        <el-col v-bind="styleResponsive ? { lg: 8, md: 12 } : { span: 8 }">
          <el-form-item label="用途类型:" prop="managementCategory">
            <DictSelection
              dictName="管理类别"
              v-model="form.managementCategory"
              :disabled="type == 'detail'"
            ></DictSelection>
          </el-form-item>
        </el-col>
        <el-col v-bind="styleResponsive ? { lg: 8, md: 12 } : { span: 8 }">
          <el-form-item label="申请机构:" prop="managementCategory">
            <deptSelect
              :disabled="type == 'detail'"
              v-model="form.useDeptId"
              @changeGroup="searchDeptNodeClick"
            />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="申请人" prop="userId">
            <el-select
              :disabled="type == 'detail'"
              v-model="form.userId"
              @change="changeExecutor"
              size="small"
              style="width: 100%"
              filterable
            >
              <el-option
                v-for="item in executorList"
                :key="item.id"
                :value="item.id"
                :label="item.name"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col v-bind="styleResponsive ? { lg: 8, md: 12 } : { span: 8 }">
          <el-form-item label="审批流程:" prop="processId">
            <el-select
              filterable
              clear
              size="small"
              v-model="form.processId"
              :disabled="type == 'detail'"
              placeholder="请选择"
              style="width: 100%"
            >
              <el-option
                :key="item.id"
                :value="item.id"
                :label="item.name"
                v-for="item in bpmList"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <headerTitle title="租赁明细" style="margin-top: 15px"></headerTitle>
      <ele-pro-table
        ref="table"
        :columns="columns"
        :datasource="deviceList"
        row-key="id"
        height="30vh"
        :needPage="false"
      >
        <template v-slot:toolbar>
          <div
            class="add-product"
            @click="addEquipment"
            v-if="type != 'detail'"
          >
            <i class="el-icon-circle-plus-outline"></i>
          </div>
        </template>
        <template v-slot:modelType="{ row }">
          <span>{{ row.category.modelType }}</span>
        </template>
        <template v-slot:specification="{ row }">
          <span>{{ row.category.specification }}</span>
        </template>

        <template v-slot:action="{ row }">
          <el-popconfirm
            v-if="type != 'detail'"
            class="ele-action"
            title="确定要删除吗？"
            @confirm="del(row.id)"
          >
            <template v-slot:reference>
              <el-link type="danger" :underline="false" icon="el-icon-delete">
                删除
              </el-link>
            </template>
          </el-popconfirm>
        </template>
      </ele-pro-table>
    </el-form>

    <template v-slot:footer>
      <el-button @click="cancel">取消</el-button>

      <el-button
        type="primary"
        @click="save"
        :loading="loading"
        v-if="type != 'detail'"
      >
        保存
      </el-button>
    </template>

    <!-- 选择产品 -->

    <MaterialAdd ref="materialAddRef" @chooseEquipment="confirmChoose">
    </MaterialAdd>

    <Detail
      v-if="activeComp === 'bpm' && form.processInstanceId"
      :id="form.processInstanceId"
    ></Detail>
  </ele-modal>
</template>

<script>
// import AssetsDialog from './AssetsDialog.vue';
import MaterialAdd from '@/views/maintenance/components/MaterialAdd.vue';
import Detail from '@/views/processInstance/detail.vue';
import { getUserPage } from '@/api/system/organization';

import { save,bpmPage } from '@/api/equipmentDisposal/index.js';

import deptSelect from '@/components/CommomSelect/dept-select.vue';

const defForm = {
  name: '',
  id: '', //维修工单id
  disposalType: '',
  managementCategory: '',
  code: '',
  processId: '',
  disposalTypeList: [],
  deviceList: []
};
export default {
  components: {
    // AssetsDialog,
    MaterialAdd,
    deptSelect,
    Detail

    // workList
  },
  data() {
    return {
      activeComp: 'main',
      tabOptions: [
        { key: 'main', name: '处置详情' },
        { key: 'bpm', name: '流程详情' }
      ],
      visible: false,
      loading: false,
      isTemplate: false,
      infoDisposalVisible: false,
      title: '设备租赁',
      type: '',
      form: { ...defForm },
      rules: {
        name: [{ required: true, message: '请选择', trigger: 'change' }],
        type: [{ required: true, message: '请选择', trigger: 'change' }],
        processId: [{ required: true, message: '请选择', trigger: 'change' }],
        disposalType: [{ required: true, message: '请选择', trigger: 'change' }]
      },
      deviceList: [],
      disposalTypeList: [],
      columns: [],
      templateName: '',
      bpmList: [],
      executorList: []
    };
  },

  computed: {
    // 是否开启响应式布局
    styleResponsive() {
      return this.$store.state.theme.styleResponsive;
    }
  },
  async created() {
    const data = await bpmPage({
      pageSize: 100,
      pageNo: 1,
      processTypeId: '1853725791034118145'
    });
    this.bpmList = data.list;
    // console.log(this.bpmList)
  },
  methods: {
    async columnsInit(type) {
      this.columns = [
        {
          columnKey: 'index',
          label: '序号',
          type: 'index',
          width: 55,
          align: 'center',
          showOverflowTooltip: true,
          fixed: 'left'
        },
        {
          prop: 'fixCode',
          label: '固资编码',
          showOverflowTooltip: true,
          width: 100,
          fixed: 'left',
          align: 'center'
        },
        {
          prop: 'codeNumber',
          label: '编码',
          width: 100,
          fixed: 'left',
          showOverflowTooltip: true,
          align: 'center'
        },
        {
          prop: 'name',
          width: 120,
          fixed: 'left',
          showOverflowTooltip: true,
          label: '名称',
          align: 'center'
        },

        {
          prop: 'modelType',
          showOverflowTooltip: true,
          slot: 'modelType',
          label: '型号',
          align: 'center'
        },
        {
          prop: 'specification',
          showOverflowTooltip: true,
          slot: 'specification',
          label: '规格',
          align: 'center'
        },
        {
          prop: 'sealingTime',
          showOverflowTooltip: true,
          label: '封存时间',
          show: type == 6,
          align: 'center'
        },
        {
          showOverflowTooltip: true,
          prop: 'postName',
          label: '使用部门',
          align: 'center'
        },
        {
          prop: 'usePerson',
          showOverflowTooltip: true,
          label: '使用人',
          align: 'center'
        },
        {
          prop: 'serviceLife',
          label: '耐用年限',
          showOverflowTooltip: true,
          align: 'center'
        },
        {
          prop: 'alreadyServiceLife',
          label: '已使用年限',
          showOverflowTooltip: true,
          align: 'center'
        },

        {
          prop: 'originalValue',
          label: '原值',
          slot: 'originalValue',
          showOverflowTooltip: true,
          align: 'center'
        },
        {
          prop: 'netWorth',
          slot: 'netWorth',
          label: '净值',
          showOverflowTooltip: true,
          align: 'center'
        },
        {
          slot: 'scrapValue',
          prop: 'scrapValue',
          label: '残值',
          showOverflowTooltip: true,
          align: 'center'
        },
        {
          prop: 'manufacturer',
          label: '生产厂家',
          showOverflowTooltip: true,
          align: 'center'
        },

        {
          prop: 'pathName',
          label: '位置',
          showOverflowTooltip: true,
          minWidth: 110,
          formatter: (_row) => {
            const positionDetail =
              _row.position &&
              _row.position.length != 0 &&
              _row.position[0].detailPosition
                ? _row.position[0].detailPosition
                : '-';
            return _row.deviceLocationName
              ? _row.deviceLocationName + '-' + positionDetail
              : '';
          },

          align: 'center'
        },
        {
          columnKey: 'action',
          label: '操作',
          width: 140,
          align: 'center',
          resizable: false,
          fixed: 'right',
          slot: 'action',
          showOverflowTooltip: true
        }
      ];
    },
    async open(row, type) {
      this.activeComp = 'main';

      this.type = type;

      if (type != 'add') {
        this.form = JSON.parse(JSON.stringify(row));
        this.form.disposalType = this.form.disposalType + '';
        this.form.managementCategory = this.form.managementCategory + '';
        this.deviceList = this.form.deviceList;
        this.disposalTypeList = this.form.disposalTypeList;
      }
      this.columnsInit(this.form.disposalType);
      this.visible = true;
    },
    del(id) {
      this.deviceList = this.deviceList.filter((item) => item.id != id);
    },
    cancel() {
      this.form = { ...defForm };
      this.deviceList = [];
      this.disposalTypeList = [];
      console.log(this.deviceList, 'this.deviceList');
      this.visible = false;
    },

    addEquipment() {
      this.$refs.materialAddRef.open(null, null, true, this.deviceList);
    },
    // 确定选择
    confirmChoose(data) {
      this.deviceList.push(...data);
    },
    //选择部门(搜索)
    searchDeptNodeClick(info, row) {
      if (info) {
        const params = { groupId: info };
        this.getUserList(params);
        this.form.useDeptName = row.name;
      } else {
        this.form.executeGroupId = null;
      }
    },
    // 人员
    async getUserList(params) {
      try {
        let data = { pageNum: 1, size: -1 };
        // 如果传了参数就是获取巡点检人员数据
        if (params) {
          data = Object.assign(data, params);
        }
        const res = await getUserPage(data);
        this.executorList = res.list;
      } catch (error) {}
    },
    // 人员选择
    changeExecutor(val) {
      if (val) {
        this.form.userId = val;
        this.form.userName = this.executorList.filter(
          (item) => item.id === val
        )[0].name;
      }
    },
    /* 保存编辑 */
    async save() {
      if (this.deviceList.length == 0) {
        this.$message.error('请选择处置对象！');
        return;
      }

      this.form.deviceList = this.deviceList;
      this.form.disposalTypeList = this.disposalTypeList;
      this.$refs.form.validate(async (valid) => {
        if (valid) {
          this.loading = true;
          save(this.form)
            .then((res) => {
              this.loading = false;
              this.$message.success('成功');
              this.cancel();
              this.$emit('refresh');
            })
            .catch((e) => {
              this.loading = false;
            });
        }
      });
    }
  }
};
</script>
<style lang="scss" scoped>
.basic-details-title {
  margin: 10px 0;
}
.title {
  font-size: 16px;
  line-height: 45px;
}
.add-product {
  width: 100%;
  display: flex;
  align-items: center;
  // justify-content: flex-end;
  font-size: 30px;
  color: #1890ff;
  margin: 10px 0;
  cursor: pointer;
}
</style>
