<template>
  <ele-modal
    :visible.sync="visible"
    :title="title"
    width="80vw"
    append-to-body
    @close="cancel"
    :maxable="true"
  >
    <el-form
      ref="form"
      :model="form"
      :rules="rules"
      label-width="90px"
      class="create-form"
    >
      <el-row :gutter="15">
        <el-col v-bind="styleResponsive ? { lg: 6, md: 12 } : { span: 6 }">
          <el-form-item label="编码:">
            <el-input
              :maxlength="20"
              v-model="form.unqualifiedProductsCode"
              disabled
            />
          </el-form-item>
        </el-col>
        <el-col v-bind="styleResponsive ? { lg: 6, md: 12 } : { span: 6 }">
          <el-form-item label="来源编码:">
            <el-input :maxlength="20" v-model="form.sourceCode" disabled />
          </el-form-item>
        </el-col>
        <el-col v-bind="styleResponsive ? { lg: 6, md: 12 } : { span: 6 }">
          <el-form-item label="数量:">
            <el-input :maxlength="20" v-model="form.quantity" disabled />
          </el-form-item>
        </el-col>

        <el-col v-bind="styleResponsive ? { lg: 6, md: 12 } : { span: 6 }">
          <el-form-item label="工艺路线:">
            <el-input
              @click.native="openVersion"
              clearable
              v-model="form.produceRoutingName"
            />
          </el-form-item>
        </el-col>
        <el-col v-bind="styleResponsive ? { lg: 6, md: 12 } : { span: 6 }">
          <el-form-item label="工序:">
            <el-select
              style="width: 100%"
              v-model="form.taskId"
              placeholder="请选择"
              clearable
              @change="produceTaskChange"
            >
              <el-option
                v-for="item in produceTaskList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col v-bind="styleResponsive ? { lg: 6, md: 12 } : { span: 6 }">
          <el-form-item label="批次号:">
            <el-input :maxlength="20" v-model="form.batchNo" disabled />
          </el-form-item>
        </el-col>
      </el-row>
      <!--  -->
      <el-table :data="form.poList" border height="40vh">
        <el-table-column label="序号" align="center" width="60">
          <template slot-scope="scope">
            <span>{{ scope.$index + 1 }}</span>
          </template>
        </el-table-column>

        <el-table-column label="产品名称" align="center" prop="categoryName">
        </el-table-column>
        <el-table-column label="产品编码" align="center" prop="categoryCode">
        </el-table-column>
        <el-table-column label="牌号" align="center" prop="brandNum">
        </el-table-column>
        <el-table-column label="刻码" align="center" prop="engrave">
          <template slot-scope="scope">
            <el-form-item
              label-width="0px"
              :prop="'poList.' + scope.$index + '.engrave'"
            >
              <el-input
                v-model="scope.row.engrave"
                size="small"
                style="width: 100%"
                placeholder="输入刻码"
              ></el-input>
            </el-form-item>
          </template>
        </el-table-column>
        <!-- <el-table-column label="型号" align="center" prop="model">
        </el-table-column> -->
        <!--        <el-table-column label="规格" align="center" prop="specification">-->
        <!--        </el-table-column>-->

        <el-table-column label="数量" align="center" prop="unqualifiedQuantity">
          <template slot-scope="scope">
            <el-form-item
              label-width="0px"
              :prop="'poList.' + scope.$index + '.unqualifiedQuantity'"
              :rules="[
                {
                  required: true,
                  message: '请输入数量',
                  trigger: 'blur'
                },
                { validator: validatePass, trigger: 'change' }
              ]"
            >
              <el-input
                v-model.number="scope.row.unqualifiedQuantity"
                size="small"
                style="width: 100%"
                placeholder="输入数量"
                @input="
                  scope.row.measureQuantity = scope.row.unqualifiedQuantity
                "
              ></el-input>
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column
          label="工艺路线"
          align="center"
          prop="produceRoutingName"
        >
        </el-table-column>
        <el-table-column label="工序" align="center" prop="produceTaskName">
        </el-table-column>

        <el-table-column
          label="不良类型"
          align="center"
          prop="badTypeId"
          width="180"
        >
          <template v-slot="{ row, $index }">
            <el-form-item
              label-width="0px"
              :prop="'poList.' + $index + '.badTypeId'"
              :rules="{
                // required: true,
                message: '请选择不良类型',
                trigger: 'blur'
              }"
            >
              <el-select
                v-model="row.badTypeId"
                placeholder="请选择不良类型"
                size="small"
                style="width: 100%"
                remote
                filterable
                :remote-method="getBadTypeList"
                clearable
                @change="badTypeChange(row)"
              >
                <el-option
                  v-for="item in badTypeList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </template>
        </el-table-column>

        <el-table-column
          label="不良名称"
          align="center"
          prop="badNameId"
          width="180"
        >
          <template v-slot="{ row, $index }">
            <el-form-item
              label-width="0px"
              :prop="'poList.' + $index + '.badNameId'"
              :rules="{
                // required: true,
                message: '请选择不良名称',
                trigger: 'blur'
              }"
            >
              <el-select
                v-model="row.badNameId"
                placeholder="请选择不良名称"
                size="small"
                style="width: 100%"
                remote
                filterable
                :remote-method="(name) => getBadNameList(name, row.badTypeId)"
                clearable
                @change="badNameChange(row)"
              >
                <el-option
                  v-for="item in badNameList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </template>
        </el-table-column>

        <el-table-column
          label="原因类型"
          align="center"
          prop="reasonTypeId"
          width="180"
        >
          <template v-slot="{ row, $index }">
            <el-form-item
              label-width="0px"
              :prop="'poList.' + $index + '.reasonTypeId'"
              :rules="{
                // required: true,
                message: '请选择不良原因类型',
                trigger: 'blur'
              }"
            >
              <el-select
                v-model="row.reasonTypeId"
                placeholder="请选择原因类型"
                size="small"
                style="width: 100%"
                remote
                filterable
                :remote-method="getReasonTypeList"
                clearable
                @change="reasonTypeChange(row)"
              >
                <el-option
                  v-for="item in reasonTypeList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </template>
        </el-table-column>

        <el-table-column
          label="原因"
          align="center"
          prop="unqualifiedReason"
          width="180"
        >
          <template slot-scope="scope">
            <el-form-item
              label-width="0px"
              :prop="'poList.' + scope.$index + '.unqualifiedReason'"
              :rules="{
                required: true,
                message: '请输入原因',
                trigger: 'blur'
              }"
            >
              <el-input
                v-model="scope.row.unqualifiedReason"
                size="small"
                style="width: 100%"
                placeholder="输入原因"
              ></el-input>
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="70">
          <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="addEquipment">
        <i class="el-icon-circle-plus-outline"></i>
      </div>
    </el-form>
    <template v-slot:footer>
      <el-button @click="cancel">取消</el-button>
      <el-button type="primary" @click="save" :loading="loading">
        确定
      </el-button>
    </template>

    <!-- 选择产品 -->
    <EquipmentDialog ref="equipmentRefs" @choose="confirmChoose">
    </EquipmentDialog>
    <ProductionVersion
      ref="versionRefs"
      @changeProduct="changeProduct"
    ></ProductionVersion>
  </ele-modal>
</template>

<script>
  import EquipmentDialog from '../components/EquipmentDialog.vue';
  import ProductionVersion from '@/components/ProductionVersion/ProductionVersion.vue';
  import { getProduceTaskList } from '@/api/aps';
  import {
    unqualifiedProductsAdd,
    updateData,
    getDetail,
    deleteUnacceptedProductDetail,
    getById
  } from '@/api/unacceptedProduct/index';
  import { getList as getBadNameList } from '@/api/unacceptedProduct/unqualifiedName';
  import { getList as getBadTypeList } from '@/api/unacceptedProduct/unqualifiedType';
  import { getList as getReasonTypeList } from '@/api/unacceptedProduct/reasonType';

  export default {
    components: {
      EquipmentDialog,
      ProductionVersion
    },
    data() {
      return {
        validatePass: (rule, value, callback) => {
          if (!value) {
            callback(new Error('数量不能为0'));
          } else {
            callback();
          }
        },
        id: '',
        visible: false,
        loading: false,
        produceTaskList: [],
        form: {
          poList: [],
          unqualifiedProductsCode: '',
          sourceCode: '',
          batchNo: '',
          brandNum: '',
          categoryCode: '',
          categoryId: '',
          categoryName: '',
          specification: '',
          modelType: '',
          produceRoutingId: '',
          produceRoutingName: '',
          taskId: '',
          taskName: '',
          quantity: '',
          measureQuantity: '',
          measureUnit: '',
          weight: '',
          weightUnit: '',
          qualityType: ''
        },
        // 表单验证规则
        rules: {
          deliveryTime: [
            { required: true, message: '请选择交付日期', trigger: 'change' }
          ]
        },

        title: '创建',
        // 不良品类型列表
        badTypeList: [],
        // 不良名称列表
        badNameList: [],
        // 原因类型列表
        reasonTypeList: []
      };
    },

    computed: {
      // 是否开启响应式布局
      styleResponsive() {
        return this.$store.state.theme.styleResponsive;
      }
    },
    created() {
      this.getBadTypeList();
      this.getBadNameList();
      this.getReasonTypeList();
    },
    methods: {
      open(row, type) {
        this.visible = true;
        if (type == 'add') {
          this.title = '创建';
          this.form = row;
          this.getProduceTaskList();
          return;
        }
        console.log(row, 'row');
        if (row) {
          this.title = '修改';
          this.getDetail(row);
        } else {
          this.title = '创建';
        }
      },
      //选择工艺路线
      openVersion() {
        this.$refs.versionRefs.open();
      },
      //工艺路线回调
      changeProduct(data) {
        this.form.produceRoutingId = data.id;
        this.form.produceRoutingName = data.name;
        this.form.taskId = '';
        this.form.taskName = '';
        if (this.title == '修改') {
          this.form.poList.forEach((item) => {
            item.produceRoutingId = data.id;
            item.produceRoutingName = data.name;
            item.produceTaskId = '';
            item.produceTaskName = '';
          });
        }

        this.getProduceTaskList();
      },
      async getProduceTaskList() {
        const res = await getProduceTaskList({
          isDetail: true,
          pageNum: 1,
          routingId: this.form.produceRoutingId,
          size: -1
        });
        this.produceTaskList = res.list;
      },
      produceTaskChange() {
        if (!this.form.taskId) {
          return;
        }
        this.form.taskName = this.produceTaskList.find(
          (item) => item.id == this.form.taskId
        ).name;
        this.form.poList.forEach((item, index) => {
          this.$set(
            this.form.poList[index],
            'produceRoutingId',
            this.form.produceRoutingId
          );
          this.$set(
            this.form.poList[index],
            'produceRoutingName',
            this.form.produceRoutingName
          );
          this.$set(this.form.poList[index], 'produceTaskId', this.form.taskId);
          this.$set(
            this.form.poList[index],
            'produceTaskName',
            this.form.taskName
          );
        });
      },

      async getDetail(row) {
        console.log(row.id, 'row.id');
        // this.form = row;

        const data = await getById(row.id);
        this.form.id = row.id;
        this.form.unqualifiedProductsCode = data.unqualifiedProductsCode;
        this.form.sourceCode = data.sourceCode;
        this.form.batchNo = data.batchNo;
        this.form.brandNum = data.brandNum;
        this.form.categoryCode = data.categoryCode;
        this.form.categoryId = data.categoryId;
        this.form.categoryName = data.categoryName;
        this.form.specification = data.specification;
        this.form.modelType = data.modelType;
        this.form.produceRoutingId = data.produceRoutingId;
        this.form.produceRoutingName = data.produceRoutingName;
        this.form.taskId = data.taskId;
        this.form.taskName = data.taskName;
        this.form.quantity = data.quantity;

        this.form.measureQuantity = data.measureQuantity;
        this.form.measureUnit = data.measureUnit;
        this.form.weight = data.weight;
        this.form.weightUnit = data.weightUnit;

        this.form.poList = data.poList;

        console.log(this.form);

        // getDetail(row.id).then((res) => {
        //   // this.getProduceTaskList();
        //   // this.form.poList = res;
        // });
      },
      cancel() {
        this.form = {
          poList: [],
          unqualifiedProductsCode: '',
          sourceCode: '',
          batchNo: '',
          brandNum: '',
          categoryCode: '',
          categoryId: '',
          categoryName: '',
          weight: '',
          specification: '',
          modelType: '',
          produceRoutingId: '',
          produceRoutingName: '',
          taskId: '',
          taskName: '',
          measureQuantity: '',
          measureUnit: '',
          weight: '',
          weightUnit: ''
        };
        this.$refs.form.clearValidate();
        this.visible = false;
      },
      // 删除产品
      handleDeleteItem(index, id) {
        this.$confirm('确认删除吗？', '提示', {
          confirmButtonText: '确定',
          cancleButtonText: '取消',
          type: 'warning'
        })
          .then((res) => {
            if (id) {
              deleteUnacceptedProductDetail([id]).then((res) => {
                this.form.poList.splice(index, 1);
              });
            } else {
              this.form.poList.splice(index, 1);
            }
          })
          .catch(() => {});

        // this.inputNumber();
      },
      addEquipment() {
        this.$refs.equipmentRefs.open();
      },
      /* 保存编辑 */
      save() {
        console.log(this.form.poList);
        this.$refs.form.validate((valid) => {
          if (!valid) {
            return false;
          }
          if (!this.form.poList.length) {
            return this.$message.warning('产品列表不能为空！');
          }
          for (let key in this.form) {
            if (key.includes('create')) {
              this.form[key] = '';
            }
          }
          this.form.poList.forEach((item) => {
            for (let key in item) {
              if (key.includes('create')) {
                item[key] = '';
              }
            }
          });
          this.loading = true;

          if (this.title == '创建') {
            unqualifiedProductsAdd(this.form)
              .then((res) => {
                this.loading = false;
                this.$message.success('成功');
                this.cancel();
                this.$emit('refresh');
              })
              .catch((e) => {
                this.loading = false;
              });
          }

          if (this.title == '修改') {
            updateData({ ...this.form, id: this.id })
              .then((res) => {
                this.loading = false;
                this.$message.success('成功');
                this.cancel();
                this.$emit('refresh');
              })
              .catch((e) => {
                this.loading = false;
              });
          }
        });
      },

      // 确定选择
      confirmChoose(data) {
        console.log(data);
        this.form.poList = [];

        let list = [];
        list = data.map((item, index) => {
          if (item.productCode) {
            return {
              // 不良品类型
              badTypeId: null,
              // 不良类型名称
              badTypeName: null,
              // 不良品名称id
              badNameId: null,
              // 不良品名称
              badNameName: null,
              // 原因类型id
              reasonTypeId: null,
              // 原因类型名称
              reasonTypeName: null,
              // 原因
              unqualifiedReason: '',
              ...item
            };
          } else {
            return {
              categoryCode: item.code,
              categoryName: item.name,
              categoryId: item.id,
              brandNum: item.brandNum,
              batchNo: item.batchNo,
              specification: item.specification,
              modelType: item.modelType,
              engrave: '',
              unqualifiedQuantity: '',
              produceRoutingId: '',
              produceRoutingName: '',
              produceTaskId: '',
              produceTaskName: '',
              measureQuantity: '',
              measureUnit: item.measuringUnit,
              weight: item.netWeight,
              weightUnit: item.weightUnit,
              // 不良品类型
              badTypeId: null,
              // 不良类型名称
              badTypeName: null,
              // 不良品名称id
              badNameId: null,
              // 不良品名称
              badNameName: null,
              // 原因类型id
              reasonTypeId: null,
              // 原因类型名称
              reasonTypeName: null,
              // 原因
              unqualifiedReason: ''
            };
          }
        });
        this.form.categoryCode = data[0].code;
        this.form.categoryName = data[0].name;
        this.form.categoryId = data[0].id;
        this.form.brandNum = data[0].brandNum;
        this.form.batchNo = data[0].batchNo;
        this.form.specification = data[0].specification;
        this.form.modelType = data[0].modelType;
        this.form.measureQuantity = '';
        this.form.measureUnit = data[0].measuringUnit;
        this.form.weight = data[0].netWeight;
        this.form.weightUnit = data[0].weightUnit;
        this.form.quantity = data.length;

        this.form.poList = this.form.poList.concat(list);

        this.produceTaskChange();
        // this.inputNumber();
      },

      inputNumber() {
        this.form.unqualifiedQuantity = 0;
        this.form.poList.forEach((item) => {
          this.form.unqualifiedQuantity +=
            Number(item.unqualifiedQuantity) || 0;
        });
      },
      // 查询不良类型
      async getBadTypeList(name = '') {
        const res = await getBadTypeList({
          pageNum: 1,
          size: 50,
          name: name
        });
        console.log('this.badTypeList', this.badTypeList);
        this.badTypeList = res.list;
      },
      // 查询不良名称
      async getBadNameList(name = '', badTypeId = 0) {
        const res = await getBadNameList({
          pageNum: 1,
          size: 50,
          name: name,
          badTypeId: badTypeId
        });
        console.log('this.badNameList', this.badNameList);
        this.badNameList = res.list;
      },
      // 查询原因类型
      async getReasonTypeList(name = '') {
        const res = await getReasonTypeList({
          pageNum: 1,
          size: 50,
          name: name
        });
        console.log('this.reasonTypeList', this.reasonTypeList);
        this.reasonTypeList = res.list;
      },
      // 不良类型改变
      badTypeChange(row) {
        row.badTypeName = null;
        // 赋值badTypeName
        const badType = this.badTypeList.find(
          (item) => item.id === row.badTypeId
        );
        if (badType) {
          row.badTypeName = badType.name;
        }
        this.getBadNameList('', row.badTypeId);
      },
      // 不良名称改变
      badNameChange(row) {
        // 赋值badNameName
        const badItem = this.badNameList.find(
          (item) => item.id === row.badNameId
        );
        if (badItem) {
          row.badNameName = badItem.name;
        }
      },
      // 原因类型改变
      reasonTypeChange(row) {
        row.reasonTypeName = null;
        // 赋值reasonTypeName
        const reasonType = this.reasonTypeList.find(
          (item) => item.id === row.reasonTypeId
        );
        if (reasonType) {
          row.reasonTypeName = reasonType.name;
        }
      }
    },
    watch: {
      'form.produceRoutingId': {
        handler(val) {
          this.getProduceTaskList();
        }
      }
    }
  };
</script>
<style lang="scss" scoped>
  .basic-details-title {
    margin: 10px 0;
  }

  .add-product {
    width: 100%;
    display: flex;
    align-items: center;
    justify-content: flex-end;
    font-size: 30px;
    color: #1890ff;
    margin: 10px 0;
    cursor: pointer;
  }

  .create-form .el-form-item {
    margin-bottom: 15px !important;
  }
</style>
