<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="repairCode"
            v-if="type != 'edit'"
          >
            <el-input v-model="form.repairCode" disabled />
          </el-form-item>
          <el-form-item label="工单编码:" prop="repairCode" v-else>
            <el-input
              v-model="form.repairCode"
              @click.native="addRepair"
              placeholder="请选择工单"
            />
          </el-form-item>
        </el-col>
        <el-col v-bind="styleResponsive ? { lg: 8, md: 12 } : { span: 8 }">
          <el-form-item label="工单名称:" prop="repairName">
            <el-input v-model="form.repairName" disabled />
          </el-form-item>
        </el-col>
       
        <el-col v-bind="styleResponsive ? { lg: 8, md: 12 } : { span: 8 }">
          <el-form-item label="领用部门:" prop="receivingDeptName">
            <el-input v-model="form.receivingDeptName" disabled />
          </el-form-item>
        </el-col>
        <el-col v-bind="styleResponsive ? { lg: 8, md: 12 } : { span: 8 }">
          <el-form-item label="领用人:" prop="recipientName">
            <el-input v-model="form.recipientName" disabled />
          </el-form-item>
        </el-col>
        <el-col v-bind="styleResponsive ? { lg: 8, md: 12 } : { span: 8 }">
          <el-form-item label="使用时间:" prop="usageTime">
            <el-date-picker
              style="width: 100%"
              v-model="form.usageTime"
              type="date"
              placeholder="选择"
              :disabled="type == 'detail'"
              value-format="yyyy-MM-dd"
            >
            </el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="使用部门" prop="useDeptName">
            <el-input v-model="form.useDeptName" :disabled="type == 'detail'" />

            <!-- <deptSelect
              :disabled="type == 'detail'"
              v-model="form.useDeptId"
              @changeGroup="searchDeptNodeClick"
            /> -->
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="使用人" prop="userName">
            <el-input v-model="form.userName" :disabled="type == 'detail'" />

            <!-- <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: 24, md: 24 } : { span: 16 }">
          <el-form-item label="用途:" prop="purpose">
            <el-input
              v-model="form.purpose"
              type="textarea"
              :rows="2"
              :disabled="type == 'detail'"
            />
          </el-form-item>
        </el-col> </el-row
    >
    <headerTitle title="设备信息" style="margin-top: 15px"></headerTitle>
    <ele-pro-table
      ref="table"
      :columns="deviceColumns"
      :datasource="deviceList"
      row-key="id"
      height="20vh"
      :needPage="false"
    >
      <template v-slot:toolbar>
        <div
          class="add-product"
          @click="materialAdd"
          v-if="type != 'detail' && !form.repairCode"
        >
          <i class="el-icon-circle-plus-outline"></i>
        </div>
      </template>
      <template v-slot:modelType="{ row }">
        <span>{{ (row.category && row.category.modelType) || row.model }}</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, 1)"
        >
          <template v-slot:reference>
            <el-link type="danger" :underline="false" icon="el-icon-delete">
              删除
            </el-link>
          </template>
        </el-popconfirm>
      </template>
    </ele-pro-table>
    <headerTitle title="备品备件信息" style="margin-top: 15px"></headerTitle>
       
    <ele-pro-table
      ref="table"
      :columns="columns"
      :datasource="tableList"
      row-key="id"
      height="20vh"
      :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:totalCount="{ row, $index }" v-if="type != 'detail'">
        <el-input
          type="number"
          placeholder="请输入"
          v-model="row.totalCount"
          @input="handleInput(row, $index)"
        />
      </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 v-if="type != 'detail'">
      <el-button @click="cancel">取消</el-button>
      <!-- <el-button type="primary" @click="save" :loading="loading">
        保存
      </el-button> -->
      <el-button type="primary" @click="save" :loading="loading">
        提交
      </el-button>
    </template>

    <!-- 选择产品 -->
    <AssetsDialog ref="equipmentRefs" :assetType="6" @choose="confirmChoose">
    </AssetsDialog>
    <MaterialAdd ref="materialAddRef" @chooseEquipment="chooseEquipment">
    </MaterialAdd>
    <workList ref="workListRef" @open="init"> </workList>
    <Detail
      v-if="activeComp === 'bpm' && form.processInstanceId"
      :id="form.processInstanceId"
    ></Detail>
  </ele-modal>
</template>

<script>
import AssetsDialog from './AssetsDialog.vue';
import workList from './workList.vue';
import MaterialAdd from '@/views/maintenance/components/MaterialAdd.vue';
import deptSelect from '@/components/CommomSelect/dept-select.vue';
import { getUserPage } from '@/api/system/organization';
import Detail from '@/views/processInstance/detail.vue';
import { save } from '@/api/maintenance/repair';
import { detailsId } from '@/api/sparePartsApply/index.js';
const defForm = {
  name: '',
  repairId: '', //维修工单id
  repairCode: '',
  code: '',
  repairName: '',
  deviceName: '',
  fixCode: '',
  deviceCode: '',
  type: '4', //类型
  status: '1', //状态
  purpose: '',
  userId: '', //使用人id
  userName: '',
  useDeptId: '', //使用部门
  useDeptName: '',
  warehouseId: '',
  recipientId: 0, //领用人id
  recipientName: '', //领用人名称
  receivingDeptId: 0, //领用部门id
  receivingDeptName: '', //领用部门id
  usageTime: '', //使用时间 //详情信息
  detailList: [],
  deviceList: []
};
export default {
  components: {
    AssetsDialog,
    MaterialAdd,
    workList,
    deptSelect,Detail
  },
  data() {
    return {
      activeComp: 'main',
      tabOptions: [
        { key: 'main', name: '处置详情' },
        { key: 'bpm', name: '流程详情' }
      ],
      visible: false,
      loading: false,
      title: '备品备件申请单',
      type: '',
      executorList: [],
      form: { ...defForm },
      rules: {
        deviceName: [{ required: true, message: '请选择', trigger: 'change' }],
        useDeptName: [{ required: true, message: '请输入', trigger: 'change' }],
        userName: [{ required: true, message: '请输入', trigger: 'change' }],
      },
      sparePartsApplyList: [],
      tableList: [],
      deviceList: [],
      columns: [],
      deviceColumns: [
        {
          columnKey: 'index',
          label: '序号',
          type: 'index',
          width: 55,
          align: 'center',
          showOverflowTooltip: true,
          fixed: 'left'
        },
        {
          prop: 'fixCode',
          label: '固资编码',
          showOverflowTooltip: true,
          align: 'center'
        },
        {
          prop: 'codeNumber',
          label: '编码',
          showOverflowTooltip: true,
          align: 'center'
        },
        {
          prop: 'name',
          showOverflowTooltip: true,
          label: '名称',
          align: 'center'
        },

        {
          prop: 'modelType',
          showOverflowTooltip: true,
          label: '型号',
          slot: 'modelType',
          align: 'center'
        },
        // {
        //   prop: 'specification',
        //   showOverflowTooltip: true,
        //   label: '规格',
        //   slot: 'action',
        //   align: 'specification'
        // },
        // {
        //   showOverflowTooltip: true,
        //   prop: 'postName',
        //   label: '使用部门',
        //   align: 'center'
        // },
        // {
        //   prop: 'usePerson',
        //   showOverflowTooltip: true,
        //   label: '使用人',
        //   align: 'center'
        // },
        {
          columnKey: 'action',
          label: '操作',
          width: 140,
          align: 'center',
          resizable: false,
          fixed: 'right',
          slot: 'action',
          showOverflowTooltip: true
        }
      ]
    };
  },

  computed: {
    // 是否开启响应式布局
    styleResponsive() {
      return this.$store.state.theme.styleResponsive;
    }
  },
  created() {},
  methods: {
    addRepair() {
      this.$refs.workListRef.open();
    },
    materialAdd() {
      this.$refs.materialAddRef.open(null, null, true, this.deviceList);
    },
    // 确定选择
    chooseEquipment(data) {
      this.deviceList.push(...data);
    },
    // 出库数量限制
    handleInput(row, index) {
      if (row.totalCount > row.measureQuantity) {
        this.$set(this.tableList[index], 'totalCount', row.measureQuantity);
      }
    },

    async open(row, type) {
      this.activeComp='main'
      this.type = type;
      this.columns = [
        {
          columnKey: 'index',
          label: '序号',
          type: 'index',
          width: 55,
          align: 'center',
          showOverflowTooltip: true,
          fixed: 'left'
        },

        {
          prop: 'categoryCode',
          label: '物品编码',
          align: 'center'
        },
        {
          prop: 'categoryName',
          label: '物品名称',
          align: 'center'
        },

        {
          prop: 'categoryModel',
          label: '型号',
          align: 'center'
        },
        {
          prop: 'specification',
          label: '规格',
          align: 'center'
        },
        {
          prop: 'level',
          label: '级别',
          align: 'center'
        },
        {
          prop: 'totalCount',
          label: '数量',
          align: 'center',
          slot: 'totalCount'
        },
        {
          prop: 'measureQuantity',
          label: '库存',
          align: 'center',
          show: type != 'detail'
        },
        {
          prop: 'measureUnit',
          label: '计量单位',
          align: 'center'
        },
        {
          prop: 'warehouseName',
          label: '仓库',
          align: 'center'
        },
        {
          columnKey: 'action',
          label: '操作',
          width: 140,
          align: 'center',
          resizable: false,
          fixed: 'right',
          slot: 'action',
          showOverflowTooltip: true
        }
      ];
      if (type != 'detail') {
        this.init(row);
      } else {
        const data = await detailsId(row.id);
        this.form = data;
        if (this.form.useDeptId) {
          this.getUserList({ groupId: this.form.useDeptId });
        }
        this.tableList = data.detailList;
        this.deviceList = data.deviceList;
      }

      this.visible = true;
    },
    del(id, type) {
      if (type == 1) {
        this.deviceList = this.deviceList.filter((item) => item.id != id);
        return;
      }
      this.tableList = this.tableList.filter((item) => item.id != id);
    },
    cancel() {
      this.sparePartsApplyList = [];
      this.tableList = [];
      this.deviceList = [];
      this.form = { ...defForm };
      this.visible = false;
    },
    init(row) {
      if (!row) {
        return;
      }
      this.form.repairCode = row.code;
      this.form.repairName = row.planName;
      this.form.repairId = row.id;
      this.deviceList = row.deviceList;
    },

    addEquipment() {
      this.$refs.equipmentRefs.open(this.tableList);
    },
    /* 保存编辑 */
    async save() {
      if (this.deviceList.length == 0) {
        this.$message.error('请选择设备！');
        return;
      }
      if (this.tableList.length == 0) {
        this.$message.error('请选择备品备件！');
        return;
      }
      let boolen = this.tableList.every((item) => item.totalCount > 0);
      if (!boolen) {
        this.$message.error('请输入出库数量！');
        return;
      }
      this.form.detailList = this.tableList;
      this.form.deviceList = this.deviceList;

      save(this.form)
        .then((res) => {
          this.loading = false;
          this.$message.success('成功');
          this.cancel();
          this.$emit('refresh');
        })
        .catch((e) => {
          this.loading = false;
        });
    },

    // 确定选择
    confirmChoose(data) {
      this.tableList = JSON.parse(JSON.stringify(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;
      }
    }
  }
};
</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>
