<template>
  <div>
    <headerTitle title="基本信息" style="margin-top: 15px"></headerTitle>
    <el-form
      ref="form"
      :model="form"
      :rules="rules"
      label-width="100px"
      class="create-form"
    >
      <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
    ></el-form>
    <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>

    <!-- 选择产品 -->
    <AssetsDialog ref="equipmentRefs" :assetType="6" @choose="confirmChoose">
    </AssetsDialog>
    <!-- <MaterialAdd ref="materialAddRef" @chooseEquipment="chooseEquipment">
    </MaterialAdd> -->
    <workList ref="workListRef" @open="init"> </workList>
  </div>
</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 { detailsId } from '@/api/bpm/components/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
  },
  props: {
    businessId: {
      default: ''
    },

    taskDefinitionKey: {
      default: ''
    }
  },
  data() {
    return {
      loading: false,
      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() {
    this.type = this.taskDefinitionKey == 'fqr' ? 'edit' : 'detail';
    this.open();
  },
  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() {
      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: this.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
        }
      ];
      const data = await detailsId(this.businessId);
      this.form = data;
      if (this.form.useDeptId) {
        this.getUserList({ groupId: this.form.useDeptId });
      }
      this.tableList = data.detailList;
      this.deviceList = data.deviceList;
    },
    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);
    },
 
    addEquipment() {
      this.$refs.equipmentRefs.open(this.tableList);
    },
    /* 保存编辑 */
    async getTableValue() {
      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;
      return this.form
      // save(this.form)
      //   .then((res) => {
      //     this.loading = false;
      //     this.$message.success('成功');
      //     this.cancel();
      //     this.$emit('refresh');
      //   })
      //   .catch((e) => {
      //     this.loading = 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;
    },
    // 确定选择
    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>
