<!-- 用户编辑弹窗 -->
<template>
  <el-dialog
    class="ele-dialog-form"
    :title="title"
    :visible.sync="visible"
    :before-close="handleClose"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    width="1280px"
  >
    <el-form ref="form" :model="form" :rules="rules" label-width="120px">
      <el-row>
        <el-col :span="8">
          <el-form-item label="编码:" prop="code">
            <el-input
              clearable
              v-model="form.code"
              placeholder="请输入"
              disabled
            />
          </el-form-item>
        </el-col>

        <el-col :span="8">
          <el-form-item label="名称:" prop="name">
            <el-input
              clearable
              v-model="form.name"
              placeholder="请输入"
              :disabled="type == 'detail' || type == 'issued'"
            />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="类型:" prop="type">
            <DictSelection
              dictName="质检计划类型"
              @change="planChange"
              v-model="form.type"
              clearable
              :disabled="type == 'detail' || type == 'issued'"
            ></DictSelection>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="取样类型:" prop="qualityMode">
            <DictSelection
              dictName="取样类型"
              v-model="form.qualityMode"
              clearable
              :disabled="type == 'detail' || type == 'issued'"
            ></DictSelection>
          </el-form-item>
        </el-col>

        <el-col :span="8">
          <el-form-item label="计划来源:" prop="planSource">
            <el-select
              v-model="form.planSource"
              placeholder="请选择"
              style="width: 100%"
              clearable
              @change="planSourceChange"
              :disabled="type == 'detail' || type == 'issued'"
            >
              <el-option
                :label="item.label"
                v-for="item in sourceList"
                :key="item.value"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="计划来源编码:" prop="planSourceCode">
            <el-input v-model="form.planSourceCode" disabled />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="自动派单:" prop="autoOrder">
            <el-select
              v-model="form.autoOrder"
              placeholder="请选择"
              style="width: 100%"
              :disabled="type == 'detail' || type == 'issued'"
            >
              <el-option label="是" :value="1" />
              <el-option label="否" :value="0" />
            </el-select>
          </el-form-item>
        </el-col>

        <el-col :span="8">
          <el-form-item
            label="执行部门"
            prop="groupId"
            :rules="{
              required: form.autoOrder || type == 'issued' ? true : false,
              message: '请选择',
              trigger: 'blur'
            }"
          >
            <deptSelect
              :disabled="type == 'detail'"
              v-model="form.groupId"
              @changeGroup="searchDeptNodeClick"
            />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item
            label="执行人员"
            prop="executeId"
            :rules="{
              required: form.autoOrder || type == 'issued' ? true : false,
              message: '请选择',
              trigger: 'blur'
            }"
          >
            <el-select
              :disabled="type == 'detail'"
              v-model="form.executeId"
              @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 :span="8">
          <el-form-item label="计划开始时间:" prop="planStartTime">
            <el-date-picker
              :disabled="type == 'detail'"
              class="w100"
              v-model="form.planStartTime"
              type="date"
              value-format="yyyy-MM-dd"
            ></el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="计划结束时间:" prop="planEndTime">
            <el-date-picker
              :disabled="type == 'detail'"
              class="w100"
              v-model="form.planEndTime"
              type="date"
              value-format="yyyy-MM-dd"
            ></el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="附件:" prop="accessory">
            <fileUpload
              v-model="form.accessory"
             
            />
            
          </el-form-item>
        </el-col>
      </el-row>
      <el-table :data="form.productList" border height="30vh">
        <el-table-column label="批次号" align="center" prop="batchNo">
        </el-table-column>
        <el-table-column label="编码" align="center" prop="productCode">
        </el-table-column>
        <el-table-column label="名称" align="center" prop="productName">
        </el-table-column>

        <el-table-column label="规格" align="center" prop="specification">
        </el-table-column>
        <el-table-column label="牌号" align="center" prop="brandNo">
        </el-table-column>
        <el-table-column label="数量" align="center" prop="productNumber">
          <template slot-scope="scope">
            <el-input
              v-model="scope.row.productNumber"
              :disabled="type == 'detail' || type == 'issued'"
            />
          </template>
        </el-table-column>

        <el-table-column
          label="工艺路线"
          align="center"
          prop="produceRoutingId"
        >
          <template slot-scope="scope">
            <el-select
              v-model="scope.row.produceRoutingId"
              placeholder="请选择"
            >
              <el-option
                style="width: 100%"
                v-for="item in routeL"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              >
              </el-option>
            </el-select>
          </template>
        </el-table-column>

        <el-table-column
          label="操作"
          align="center"
          width="70"
          v-if="!form.planSourceCode"
        >
          <template slot-scope="scope">
            <el-link
              type="danger"
              :underline="false"
              @click="handleDeleteItem(scope.$index, scope.row.id)"
            >
              删除
            </el-link>
          </template>
        </el-table-column>
      </el-table>
      <div class="add-product" @click="addProduct" v-if="type != 'detail'">
        <i class="el-icon-circle-plus-outline"></i>
      </div>
      <EquipmentDialog
        ref="equipmentRefs"
        @choose="choose"
        :type="1"
        :treeIds="['9','1']"
      />
      <productionPlan ref="productionPlanRef" @choose="choose" />
      <workOrder ref="workOrderRef" @choose="choose" />
      <produceOrder ref="produceOrderRef" @choose="choose" />
      <warehousing ref="warehousingRef" @choose="choose" />
    </el-form>

    <template v-slot:footer>
      <el-button @click="handleClose">取消</el-button>
      <el-button
        v-if="type != 'detail' && type != 'issued'"
        type="primary"
        :loading="loading"
        @click="save"
      >
        保存
      </el-button>
      <el-button
        v-if="type == 'issued'"
        type="primary"
        :loading="loading"
        @click="save"
      >
        下发
      </el-button>
    </template>
  </el-dialog>
</template>

<script>
  import { save, update, planIssued } from '@/api/inspectionPlan';
  import { routeList } from '@/api/aps/index';
  import EquipmentDialog from '@/views/inspectionWork/components/EquipmentDialog';
  import productionPlan from './productionPlan';
  import workOrder from './workOrder';
  import produceOrder from './produceOrder';
  import warehousing from './warehousing';
  import { getUserPage } from '@/api/system/organization';
  import deptSelect from '@/components/CommomSelect/dept-select.vue';
  // import fileUpload from '@/components/upload/fileUpload';
  import fileUpload from '@/components/addDoc/index.vue';

  export default {
    components: {
      EquipmentDialog,
      deptSelect,
      productionPlan,
      workOrder,
      produceOrder,
      fileUpload,
      warehousing
    },
    data() {
      const defaultForm = function () {
        return {
          id: '',
          code: '',
          planSourceId: '',
          planSourceCode: '',
          name: '',
          autoOrder: 0,
          duration: '',
          status: '',
          approvalUserId: '',
          executeId: '',
          groupId: '',
          groupName: '',
          planStartTime: '',
          planEndTime: '',
          accessory: [],
          // productCode: '',
          // productName: '',
          // specification: '',
          // brandNo: '',
          // productNumber: '',
          executeName: '',
          planSource: '',
          batchNo: '',
          productList: [],
          qualityMode: '',

        
        };
      };
      return {
        defaultForm,
        // 表单数据
        form: { ...defaultForm() },
        sourceList: [],
        // 表单验证规则
        rules: {
          name: [{ required: true, message: '请输入', trigger: 'blur' }]
          // productName: [{ required: true, message: '请选择', trigger: 'blur' }]
        },
        visible: false,
        type: null,
        title: null,
        loading: false,
        listPage: [],
        executorList: [],

        routeL: []
      };
    },
    watch: {
      'form.type'(val) {
        this.sourceList =
          val == 1
            ? [{ label: '采购收货单', value: '1' }]
            : val == 2
            ? [
                { label: '生产计划', value: '2' },
                { label: '生产订单', value: '3' },
                { label: '生产工单', value: '4' }
              ]
            : [];
      }
    },
    created() {},
    methods: {
      open(type, row) {
        this.title =
          type == 'add'
            ? '新增'
            : type == 'edit'
            ? '编辑'
            : type == 'issued'
            ? '下发'
            : '详情';
        this.type = type;
        if (this.type != 'add') {
          row.accessory = row.accessory || [];
          this.form = JSON.parse(JSON.stringify(row));
          if (this.form.groupId) {
            this.getUserList({ groupId: this.form.groupId });
          }
        }
        this.visible = true;

        this.getRouteList();
      },
      planChange(value) {
        this.form.planSource = '';
        this.choose({});
      },

      planSourceChange() {
        this.choose({});
        if (this.form.planSource) {
          this.addProduct();
        }
      },
      handleDeleteItem(index) {
        this.form.productList.splice(index, 1);
      },
      addProduct() {
        if (this.form.planSource == 1) {
          this.$refs.warehousingRef.open();
        } else if (this.form.planSource == 2) {
          this.$refs.productionPlanRef.open();
        } else if (this.form.planSource == 3) {
          this.$refs.workOrderRef.open();
        } else if (this.form.planSource == 4) {
          this.$refs.produceOrderRef.open();
        } else {
          this.$refs.equipmentRefs.open();
        }
      },
      /* 保存编辑 */
      save() {
        this.$refs.form.validate((valid) => {
          if (!valid) {
            return false;
          }
          if (this.form.productList.length == 0) {
            this.$message.error('请选择产品！');

            return;
          }

    

           let isBol  = this.form.productList.every((e, i) => e.productNumber && e.produceRoutingId)
           if(!isBol) {
            this.$message.error('请完善数据');
            return;
          }

     


          this.loading = true;
          if (this.type == 'add') {
            delete this.form.id;
          }
          console.log(this.type);
          let URL =
            this.type == 'add'
              ? save
              : this.type == 'edit'
              ? update
              : planIssued;
          URL(this.form)
            .then((msg) => {
              this.loading = false;
              this.$message.success(msg);
              this.handleClose();
              this.$emit('done');
            })
            .catch((e) => {
              this.loading = false;
            });
        });
      },
      choose(data) {
        if (Array.isArray(data)) {
          this.form.productList = [];
          data.forEach((item) => {
            this.form.productList.push({
              productCode: item.code,
              productName: item.name,
              specification: item.specification,
              brandNo: item.brandNum,
              productNumber: ''
            });
          });
          return;
        }
        this.form.productList = data.productList;
        this.form.planSourceId = data.id;
        this.form.planSourceCode = data.code;
      },

      //选择部门(搜索)
      searchDeptNodeClick(info, row) {
        if (info) {
          const params = { groupId: info };
          this.getUserList(params);
          this.form.groupName = 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.executeId = val;
          this.form.executeName = this.executorList.filter(
            (item) => item.id === val
          )[0].name;
        }
      },
      restForm() {
        this.form = { ...this.defaultForm() };
        this.$nextTick(() => {
          this.$refs.form.clearValidate();
        });
      },
      handleClose() {
        this.restForm();
        this.visible = false;
      },

      getRouteList() {
        let params = { pageNum: 1, size: -1, status: 1, routeType: 3 };
        routeList(params).then((res) => {
          this.routeL = res.list || [];
        });
      }
    }
  };
</script>

<style lang="scss" scoped>
  .location-warp {
    display: flex;

    .detail {
      margin-left: 10px;
    }
  }
  :deep(.el-form-item__content .el-input-group__prepend) {
    background-color: #fff;
  }
  :deep(
      .el-dialog:not(.ele-dialog-form)
        .el-dialog__body
        .el-form
        .el-form-item:last-child
    ) {
    margin-bottom: 22px;
  }
  .add-product {
    width: 100%;
    display: flex;
    align-items: center;
    justify-content: flex-end;
    font-size: 30px;
    color: #1890ff;
    margin: 10px 0;
    cursor: pointer;
  }
</style>
