<template>
  <ele-modal :visible.sync="visible" :title="title" width="60vw" append-to-body @close="cancel">
    <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="form.repairId&&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="deviceName"
            v-if="form.repairId"
          >
            <el-input
              v-model="form.deviceName"
              disabled
              v-if="sparePartsApplyList.length == 0"
            />
            <el-select
              v-model="form.deviceName"
              style="width: 100%"
              placeholder="请选择"
              v-else
            >
              <el-option
                v-for="item in sparePartsApplyList"
                :key="item.deviceCode"
                :label="item.deviceName"
                :value="item.deviceName"
                @click.native="deviceChange(item)"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item v-else label="设备名称:" prop="deviceName">
            <el-input
              v-model="form.deviceName"
              @click.native="materialAdd"
              placeholder="请选择设备"
            />
          </el-form-item>
        </el-col>

        <el-col v-bind="styleResponsive ? { lg: 8, md: 12 } : { span: 8 }">
          <el-form-item label="固资编码:" prop="fixCode">
            <el-input v-model="form.fixCode" disabled />
          </el-form-item>
        </el-col>
        <el-col v-bind="styleResponsive ? { lg: 8, md: 12 } : { span: 8 }">
          <el-form-item label="设备编号:" prop="deviceCode">
            <el-input v-model="form.deviceCode" disabled />
          </el-form-item>
        </el-col>
        <el-col v-bind="styleResponsive ? { lg: 8, md: 12 } : { span: 8 }">
          <el-form-item label="领用部门:" prop="useDeptName">
            <el-input v-model="form.useDeptName" disabled />
          </el-form-item>
        </el-col>
        <el-col v-bind="styleResponsive ? { lg: 8, md: 12 } : { span: 8 }">
          <el-form-item label="领用人:" prop="userName">
            <el-input v-model="form.userName" 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 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="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>

    <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>
  </ele-modal>
</template>

<script>
import AssetsDialog from './AssetsDialog.vue';
import workList from './workList.vue';
import MaterialAdd from './MaterialAdd.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: '',
  usageTime: '', //使用时间 //详情信息
  detailList: []
};
export default {
  components: {
    AssetsDialog,
    MaterialAdd,
    workList
  },
  data() {
    return {
      visible: false,
      loading: false,
      title: '备品备件申请单',
      type: '',
      form: { ...defForm },
      rules: {
        deviceName: [{ required: true, message: '请选择', trigger: 'change' }]
      },
      sparePartsApplyList: [],
      tableList: [],
      columns: []
    };
  },

  computed: {
    // 是否开启响应式布局
    styleResponsive() {
      return this.$store.state.theme.styleResponsive;
    }
  },
  created() {},
  methods: {
    addRepair() {
      this.$refs.workListRef.open();
    },
    materialAdd() {
      this.$refs.materialAddRef.open();
    },
    // 出库数量限制
    handleInput(row, index) {
      if (row.totalCount > row.measureQuantity) {
        this.$set(this.tableList[index], 'totalCount', row.measureQuantity);
      }
    },
    deviceChange(item) {
      this.form.fixCode = item.fixCode;
      this.form.deviceCode = item.deviceCode;
    },
    async open(row, type) {
      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;
        this.tableList = data.detailList;
      }

      this.visible = true;
    },
    del(id) {
      this.tableList = this.tableList.filter((item) => item.id != id);
    },
    cancel() {
      this.sparePartsApplyList = [];
      this.tableList = [];
      this.form={...defForm}
      this.visible = false;
    },
    init(row) {
      console.log(row);
      if (!row) {
        return;
      }
      this.form.repairCode = row.code;
      this.form.repairName = row.planName;
      this.form.repairId = row.id;
      this.form.deviceName = row.substanceDetailVO?.name;
      this.form.fixCode = row.substanceDetailVO?.fixCode;
      this.form.deviceCode = row.substanceDetailVO?.codeNumber;
      this.sparePartsApplyList = row.sparePartsApplyList||[]
    },
    chooseEquipment(data) {
      this.form.deviceName = data.name;
      this.form.fixCode = data.fixCode;
      this.form.deviceCode = data.code;
    },
    addEquipment() {
      this.$refs.equipmentRefs.open(this.tableList);
    },
    /* 保存编辑 */
    async save() {
      if (!this.form.deviceName) {
        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;

      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));
    }
  }
};
</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>
