<template>
  <ele-modal
    custom-class="ele-dialog-form long-dialog-form"
    :centered="true"
    :visible="autogenerateDialogFlag"
    v-if="autogenerateDialogFlag"
    title="生成采购计划"
    append-to-body
    :close-on-click-modal="false"
    :width="isAuto ? '30%' : '50%'"
    :before-close="cancel"
  >
    <el-form ref="form" :model="form" class="el-form-box" v-if="!isAuto">
      <el-row>
        <!--        <headerTitle title="生成采购计划"></headerTitle>-->
        <el-col :span="24">
          <ele-pro-table
            ref="table"
            :needPage="false"
            :columns="generatePurchaseColumns"
            :max-height="300"
            :toolkit="[]"
            :selection.sync="selection"
            :datasource="form.generatePurchaseTable"
            cache-key="generatePurchaseListTable17"
            class="time-form"
          >
            <!-- 表头工具栏 -->
            <!--            <template v-slot:toolbar>-->
            <!--              <el-form-item-->
            <!--                label="选择产品："-->
            <!--                prop="generatePurchase"-->
            <!--                style="margin-bottom: 0"-->
            <!--              >-->
            <!--                <el-select-->
            <!--                  v-model="generatePurchaseList"-->
            <!--                  multiple-->
            <!--                  clearable-->
            <!--                  filterable-->
            <!--                  collapse-tags-->
            <!--                  placeholder="请选择"-->
            <!--                >-->
            <!--                  <el-option-->
            <!--                    v-for="item in commitData.productList"-->
            <!--                    :key="item.productCode"-->
            <!--                    :label="item.productName"-->
            <!--                    :value="item.productCode"-->
            <!--                  ></el-option>-->
            <!--                </el-select>-->
            <!--              </el-form-item>-->
            <!--            </template>-->
            <template v-slot:produceCycle="scope">
              <el-form-item
                :prop="
                  'generatePurchaseTable.' + scope.$index + '.produceCycle'
                "
              >
                <el-date-picker
                  style="width: 100%"
                  v-model="scope.row.produceCycle"
                  type="date"
                  disabled
                  placeholder="选择日期"
                >
                </el-date-picker>
              </el-form-item>
            </template>
            <template v-slot:productionDays="scope">
              <el-form-item
                :prop="
                  'generatePurchaseTable.' + scope.$index + '.productionDays'
                "
                :rules="{
                  required: true,
                  pattern: positiveIntegerReg(),
                  message: '请正确输入数量',
                  trigger: ['blur', 'change']
                }"
              >
                <el-input
                  @change="handleProduceDays(scope.row, scope.$index)"
                  type="number"
                  :min="1"
                  disabled
                  v-model="scope.row.productionDays"
                  style="width: 100%"
                >
                  <span slot="append">天</span>
                </el-input>
              </el-form-item>
            </template>
            <template v-slot:headerRequired="{ column }">
              <span class="is-required">{{ column.label }}</span>
            </template>
          </ele-pro-table>
        </el-col>
      </el-row>
      <!--      <el-row>-->
      <!--        <headerTitle title="生成生产计划"></headerTitle>-->
      <!--        <el-col :span="24">-->
      <!--          <el-form-item label="自动生成生产计划：" prop="generateProduce">-->
      <!--            <el-select-->
      <!--              v-model="generateProduceList"-->
      <!--              multiple-->
      <!--              clearable-->
      <!--              filterable-->
      <!--              collapse-tags-->
      <!--              placeholder="请选择"-->
      <!--            >-->
      <!--              <el-option-->
      <!--                v-for="item in commitData.productList"-->
      <!--                :key="item.productCode"-->
      <!--                :label="item.productName"-->
      <!--                :value="item.productCode"-->
      <!--              ></el-option>-->
      <!--            </el-select>-->
      <!--          </el-form-item>-->
      <!--        </el-col>-->
      <!--      </el-row>-->
      <!--      <el-row>-->
      <!--        <headerTitle title="生成项目立项"></headerTitle>-->
      <!--        <el-col :span="24">-->
      <!--          <el-form-item label="自动生成项目立项：" prop="generateProject">-->
      <!--            <el-select-->
      <!--              v-model="generateProjectList"-->
      <!--              multiple-->
      <!--              clearable-->
      <!--              filterable-->
      <!--              collapse-tags-->
      <!--              placeholder="请选择"-->
      <!--            >-->
      <!--              <el-option-->
      <!--                v-for="item in commitData.productList"-->
      <!--                :key="item.productCode"-->
      <!--                :label="item.productName"-->
      <!--                :value="item.productCode"-->
      <!--              ></el-option>-->
      <!--            </el-select>-->
      <!--          </el-form-item>-->
      <!--        </el-col>-->
      <!--      </el-row>-->
    </el-form>
    <div slot="footer" v-if="!isAuto">
      <el-button type="primary" @click="save">确定</el-button>
      <el-button @click="cancel">关闭</el-button>
    </div>
    <el-form
      ref="form"
      :model="form"
      :rules="rules"
      label-width="160px"
      class="el-form-box"
      v-if="isAuto"
    >
      <el-row>
        <el-col :span="24">
          <el-form-item label="自动生成采购计划：" prop="generatePurchase">
            <el-radio-group
              v-model="form.generatePurchase"
              @change="handleChange"
            >
              <el-radio :label="1">是</el-radio>
              <el-radio :label="0">否</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>

        <el-col :span="24">
          <el-form-item label="自动生成生产计划：" prop="generateProduce">
            <el-radio-group v-model="form.generateProduce">
              <el-radio :label="1">是</el-radio>
              <el-radio :label="0">否</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="自动生成项目立项：" prop="generateProject">
            <el-radio-group v-model="form.generateProject">
              <el-radio :label="1">是</el-radio>
              <el-radio :label="0">否</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <div slot="footer" v-if="isAuto">
      <el-button type="primary" @click="save">确定</el-button>
      <el-button @click="cancel">关闭</el-button>
    </div>
  </ele-modal>
</template>
<script>
  import {
    saleOrderCheckCBomAPI,
    saleOrderGeneratePlanAPI
  } from '@/api/saleOrder';
  import { getSaleOrderDetail } from '@/api/saleManage/saleorder';
  import { positiveIntegerReg } from 'ele-admin';

  export default {
    name: 'autogenerateDialog',
    components: {},
    data() {
      return {
        form: {
          generatePurchase: 0,
          generateProduce: 0,
          generateProject: 0,
          generatePurchaseTable: [],
          generateProduceTable: [],
          generateProjectTable: []
        },
        generatePurchaseList: [],
        generateProduceList: [],
        generateProjectList: [],
        selection: [],
        commitData: {},
        isAuto: false,
        autogenerateDialogFlag: false,
        rules: {}
      };
    },
    watch: {
      generatePurchaseList: {
        handler(newVal, oldVal) {
          if (!newVal.length) {
            return (this.form.generatePurchaseTable = []);
          }
          if (newVal.length > oldVal.length) {
            const set1 = new Set(oldVal);
            let data = newVal.filter((item) => !set1.has(item));
            data.forEach((item) => {
              let find =
                this.commitData?.productList?.find(
                  (i) => i.productCode === item
                ) || {};
              find.generatePurchase = 1;
              find.productionDays = find.productionDays || undefined;
              find.produceCycle = '';
              this.form.generatePurchaseTable.push(find);
            });
          } else {
            const set1 = new Set(newVal);
            this.form.generatePurchaseTable =
              this.form.generatePurchaseTable.filter((item) =>
                set1.has(item.productCode)
              );
          }
        },
        deep: true
      },
      generateProduceList: {
        handler(newVal, oldVal) {
          if (!newVal.length) {
            return (this.form.generateProduceTable = []);
          }
          if (newVal.length > oldVal.length) {
            const set1 = new Set(oldVal);
            let data = newVal.filter((item) => !set1.has(item));
            data.forEach((item) => {
              let find =
                this.commitData?.productList?.find(
                  (i) => i.productCode === item
                ) || {};
              find.generateProduce = 1;
              this.form.generateProduceTable.push(find);
            });
          } else {
            const set1 = new Set(newVal);
            this.form.generateProduceTable =
              this.form.generateProduceTable.filter((item) =>
                set1.has(item.productCode)
              );
          }
        },
        deep: true
      },
      generateProjectList: {
        handler(newVal, oldVal) {
          if (!newVal.length) {
            return (this.form.generateProjectTable = []);
          }
          if (newVal.length > oldVal.length) {
            const set1 = new Set(oldVal);
            let data = newVal.filter((item) => !set1.has(item));
            data.forEach((item) => {
              let find =
                this.commitData?.productList?.find(
                  (i) => i.productCode === item
                ) || {};
              find.generateProject = 1;
              this.form.generateProjectTable.push(find);
            });
          } else {
            const set1 = new Set(newVal);
            this.form.generateProjectTable =
              this.form.generateProjectTable.filter((item) =>
                set1.has(item.productCode)
              );
          }
        },
        deep: true
      }
    },
    computed: {
      generatePurchaseColumns() {
        return [
          {
            width: 45,
            type: 'selection',
            columnKey: 'selection',
            align: 'center'
          },
          {
            minWidth: 150,
            prop: 'productName',
            label: '名称',
            slot: 'productName',
            headerSlot: 'headerProductName',
            align: 'center'
          },
          {
            minWidth: 150,
            prop: 'productCode',
            label: '编码',
            slot: 'productName',
            align: 'center'
          },
          {
            minWidth: 150,
            prop: 'productionDays',
            label: '生产周期',
            slot: 'productionDays',
            headerSlot: 'headerRequired',
            align: 'center'
          },
          {
            minWidth: 170,
            prop: 'produceCycle',
            label: '到货时间',
            slot: 'produceCycle',
            headerSlot: 'headerRequired',
            align: 'center'
          },
          {
            width: 140,
            prop: 'customerExpectDeliveryDeadline',
            label: '客户期望交期',
            align: 'center'
          },
          {
            width: 140,
            prop: 'produceDeliveryDeadline',
            label: '生产交付交期',
            align: 'center'
          }
        ];
      }
    },
    methods: {
      positiveIntegerReg() {
        return positiveIntegerReg;
      },
      init(orderId, isAuto = false) {
        this.isAuto = isAuto;
        this.autogenerateDialogFlag = true;
        this.$nextTick(() => {
          this.getSaleOrderDetail(orderId);
        });
      },
      //获取订单详情
      async getSaleOrderDetail(id) {
        this.commitData = await getSaleOrderDetail(id);
        this.form.generatePurchaseTable = this.commitData.productList;
        this.form.generatePurchaseTable.forEach((item, index) => {
          this.handleProduceDays(item, index);
        });
      },
      handleProduceDays(row, index) {
        let newDate = new Date(row.customerExpectDeliveryDeadline);
        newDate.setDate(newDate.getDate() - row.productionDays);
        newDate = newDate.toISOString().split('T')[0];
        this.$set(
          this.form.generatePurchaseTable[index],
          'produceCycle',
          newDate
        );
      },
      // async save() {
      //   let saleOrderProductUpdatePOList = [
      //     ...this.form.generatePurchaseTable,
      //     ...this.form.generateProjectTable,
      //     ...this.form.generateProduceTable
      //   ];
      //   if (!saleOrderProductUpdatePOList.length)
      //     return this.$message.error('请选择生成数据');
      //   if (
      //     this.form.generatePurchaseTable.length > 0 &&
      //     this.form.generatePurchaseTable.some(
      //       (item) => !!item.productionDays == 0 || !item.produceCycle
      //     )
      //   )
      //     return this.$message.error('生产周期和到货时间不能为空');
      //   saleOrderProductUpdatePOList = saleOrderProductUpdatePOList.reduce(
      //     (acc, curr) => {
      //       const found = acc.find(
      //         (item) => item.productCode === curr.productCode
      //       );
      //       if (!found) {
      //         acc.push(curr);
      //       }
      //       return acc;
      //     },
      //     []
      //   );
      //   saleOrderProductUpdatePOList.forEach((item) => {
      //     //合并生成采购计划
      //     let generatePurchaseObj =
      //       this.form.generatePurchaseTable.find(
      //         (i) => i.productCode === item.productCode
      //       ) || {};
      //     item.generatePurchase = generatePurchaseObj.generatePurchase || 0;
      //     //合并生成生产计划计划
      //     let generateProduceObj =
      //       this.form.generateProduceTable.find(
      //         (i) => i.productCode === item.productCode
      //       ) || {};
      //     item.generateProduce = generateProduceObj.generateProduce || 0;
      //     //合并生成项目数据
      //     let generateProjectObj =
      //       this.form.generateProjectTable.find(
      //         (i) => i.productCode === item.productCode
      //       ) || {};
      //     item.generateProject = generateProjectObj.generateProject || 0;
      //   });
      //   let params = {
      //     orderId: this.commitData.id,
      //     saleOrderProductUpdatePOList
      //   };
      //   await saleOrderGeneratePlanAPI(params);
      //   this.$message.success('操作成功');
      //   this.cancel();
      // },
      async handleChange(val) {
        if (val == 1) {
          let ids = this.commitData.productList.map((i) => i.productId);
          try {
            await saleOrderCheckCBomAPI(ids);
          } catch (e) {
            return (this.form.generatePurchase = 0);
          }
        }
        if (
          val == 1 &&
          this.commitData.productList.some((item) => !item.productionDays)
        ) {
          this.$message.warning('生成采购计划生产周期不能为空，请在主数据维护');
        }
      },

      async save() {
        if (this.isAuto) {
          let isHaveProductionDays = true;
          this.commitData.productList.forEach((item) => {
            if (!item.productionDays && this.form.generatePurchase) {
              isHaveProductionDays = false;
            }
            item.generatePurchase = this.form.generatePurchase ? 1 : 0;
            item.generateProduce = this.form.generateProduce ? 1 : 0;
            item.generateProject = this.form.generateProject ? 1 : 0;
          });
          this.selection = this.commitData.productList;
          if (!isHaveProductionDays)
            return this.$message.error(
              '生成采购计划生产周期不能为空，请在主数据维护'
            );
        } else {
          if (!this.selection.length) {
            return this.$message.error('请选择需要生成采购计划的数据');
          }
          if (
            this.selection.some(
              (item) => !!item.productionDays == 0 || !item.produceCycle
            )
          )
            return this.$message.error('生产周期不能为空，请在主数据维护');
          this.selection.forEach((item) => {
            item.generatePurchase = 1;
          });
        }
        let params = {
          orderId: this.commitData.id,
          saleOrderProductUpdatePOList: this.selection
        };
        await saleOrderGeneratePlanAPI(params);
        if (this.isAuto) {
          this.$emit('handleSubmit', this.commitData.id);
        } else {
          this.$message.success('操作成功');
          this.$emit('reload');
        }
        this.cancel();
      },
      cancel() {
        this.autogenerateDialogFlag = false;
        this.form = {
          generatePurchase: 0,
          generateProduce: 0,
          generateProject: 0,
          generatePurchaseTable: [],
          generateProduceTable: [],
          generateProjectTable: []
        };
        this.generatePurchaseList = [];
        this.generateProduceList = [];
        this.generateProjectList = [];
        this.selection = [];
        this.commitData = {};
      }
    }
  };
</script>

<style scoped lang="scss"></style>
