<template>
  <ele-modal
    :visible.sync="buVisible"
    @closed="cancel"
    title="采购申请"
    custom-class="ele-dialog-form"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    width="80%"
    :maxable="true"
  >
    <el-form
      :model="formData"
      ref="formRef"
      label-width="120px"
      class="ele-body"
      :rules="rules"
    >
      <el-row :gutter="24">
        <el-col :span="8">
          <el-form-item label="需求类型" prop="demandType">
            <el-select
              v-model="formData.demandType"
              :key="formData.demandType"
              placeholder="请选择"
              style="width: 100%"
              disabled
            >
              <el-option
                v-for="item in demandTypeList"
                :key="item.dictCode"
                :label="item.dictValue"
                :value="item.dictCode"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>

        <el-col :span="8">
          <el-form-item label="计划名称" prop="name">
            <el-input placeholder="请选择" v-model="formData.name"></el-input>
          </el-form-item>
        </el-col>

        <el-col :span="8">
          <el-form-item label="备注" prop="remark">
            <el-input placeholder="备注" v-model="formData.remark"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <!-- <ele-pro-table
        ref="tableRef3"
        :columns="columns"
        :datasource="tableList"
        :need-page="false"
        :toolbar="false"
        row-key="id"
        default-expand-all
      >
        <template v-slot:action="{ row, $index }">
          <template>
            <el-link
              type="primary"
              :underline="false"
              @click="categorySelect(row)"
            >
              添加物料
            </el-link>
          </template>
        </template>
        <template v-slot:expand="{ row, $index }">
          <div
            style="
              width: calc(100% - 55px);
              min-height: 60px;
              margin-left: 55px;
            "
          >
            <ele-pro-table
              :columns="materiaList"
              :datasource="row.materialList || []"
              :need-page="false"
              height="300px"
              class="el-form-box"
              :toolkit="[]"
            ></ele-pro-table> </div
        ></template>
      </ele-pro-table> -->
      <ele-pro-table
        :columns="columns2"
        :datasource="materialList"
        :need-page="false"
        class="el-form-box"
        :toolkit="[]"
        :selection.sync="selection"
      >
        <template v-slot:toolbar>
          <el-button @click="categorySelect" type="primary">添加物料</el-button>
          <el-button @click="batchUpdateDeliveryMethod"
            >批量修改到货方式</el-button
          >
        </template>
        <template v-slot:demandQuantity="{ row }">
          <div>
            <!-- 需求数量 -->
            <el-input
              v-model="row.demandQuantity"
              placeholder="请输入"
              @input="
                (value) =>
                  (row.demandQuantity = value.replace(
                    /^(-)*(\d+)\.(\d\d\d\d\d\d).*$/,
                    '$1$2.$3'
                  ))
              "
            ></el-input>
          </div>
        </template>

        <template v-slot:purchasingCycle="{ row }">
          {{ row.purchasingCycle }}{{ row.purchasingCycleUnit }}
        </template>
        <template v-slot:purchaseQuantity="{ row }">
          <el-input
            v-model="row.purchaseQuantity"
            placeholder="请输入"
            @input="
              (value) =>
                (row.purchaseQuantity = value.replace(
                  /^(-)*(\d+)\.(\d\d\d\d\d\d).*$/,
                  '$1$2.$3'
                ))
            "
          ></el-input>
        </template>
        <template v-slot:deliveryMethod="{ row, $index }">
          <el-select
            clearable
            class="ele-block"
            v-model="row.deliveryMethod"
            placeholder="请选择"
          >
            <el-option
              label="一次性到货"
              :value="1"
              @click.native="row.timeList = null"
            />
            <el-option
              label="分批到货"
              :value="2"
              @click.native="
                handleMethod(row, $index);
                row.requireDeliveryTime = null;
              "
            />
          </el-select>
        </template>
        <template v-slot:requireDeliveryTime="{ row, $index }">
          <el-date-picker
            style="width: 100%"
            clearable
            v-model="row.requireDeliveryTime"
            type="date"
            v-if="row.deliveryMethod == 1"
            value-format="yyyy-MM-dd"
            placeholder="请选择日期"
            :pickerOptions="{
              disabledDate: (time) =>
                time.getTime() <
                new Date(new Date().setHours(0, 0, 0, 0)).getTime()
            }"
          >
          </el-date-picker>

          <el-link
            type="primary"
            :underline="false"
            v-if="row.deliveryMethod == 2"
            @click.native="handleMethod(row, $index)"
          >
            设置分批时间
          </el-link>
        </template>
        <template v-slot:imgUrl="{ row }">
          <fileMain
            v-model="row.imgUrl"
            module="main"
            :showLib="false"
            :limit="1"
          />
        </template>
        <template v-slot:files="{ row }">
          <fileMain
            v-model="row.files"
            module="main"
            :showLib="false"
            :limit="1"
          />
        </template>
        <template v-slot:action="{ row, $index }">
          <el-popconfirm
            v-if="row.isDel"
            class="ele-action"
            title="确定要删除此物料吗？"
            @confirm="remove(row, $index)"
          >
            <template v-slot:reference>
              <el-link type="danger" :underline="false" icon="el-icon-delete">
                删除
              </el-link>
            </template>
          </el-popconfirm>
        </template>
      </ele-pro-table>
    </el-form>
    <ProductModal ref="productRefs" @chooseModal="chooseModal" />
    <timeDialog ref="timeDialogRef" @chooseTime="chooseTime"></timeDialog>
    <ele-modal
      :visible.sync="batchVisible"
      title="批量选择"
      width="25vw"
      append-to-body
      @close="handleCancel"
      :maxable="true"
    >
      <el-form :model="formData2" label-width="100px">
        <el-form-item label="到货方式" prop="deliveryMethod">
          <el-select
            clearable
            v-model="formData2.deliveryMethod"
            placeholder="请选择"
          >
            <el-option label="一次性到货" :value="1" />
            <el-option
              label="分批到货"
              :value="2"
              @click.native="handleMethod()"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="要求到货时间" prop="requireDeliveryTime">
          <el-date-picker
            clearable
            v-model="formData2.requireDeliveryTime"
            type="date"
            v-show="formData2.deliveryMethod == 1"
            value-format="yyyy-MM-dd"
            placeholder="请选择日期"
            :pickerOptions="{
              disabledDate: (time) =>
                time.getTime() <
                new Date(new Date().setHours(0, 0, 0, 0)).getTime()
            }"
          >
          </el-date-picker>
          <el-link
            type="primary"
            :underline="false"
            v-show="formData2.deliveryMethod == 2"
            @click.native="handleMethod()"
          >
            设置分批时间
          </el-link>
        </el-form-item>
      </el-form>
      <template v-slot:footer>
        <el-button @click="handleCancel">取消</el-button>
        <el-button type="primary" @click="handleConfirm">确认</el-button>
      </template>
    </ele-modal>
    <div slot="footer">
      <el-button @click="cancel">取消</el-button>
      <el-button type="primary" @click="confirm">保存</el-button>
    </div>
  </ele-modal>
</template>

<script>
  import ProductModal from '@/views/materialPlan/components/ProductModal.vue';
  import timeDialog from '@/views/materialPlan/components/timeDialog.vue';
  import { getCode } from '@/api/codeManagement';
  import { save } from '@/api/materialPlan/index';

  export default {
    props: {
      orderType: {
        type: Number,
        default: 2
      }
    },
    components: {
      ProductModal,
      timeDialog
    },
    data() {
      return {
        buVisible: false,
        // tableList: []
        materialList: [],
        planData: {},
        selection: [],
        batchVisible: false,
        demandTypeList: [
          {
            dictCode: '1',
            dictValue: '生产性物资采购'
          },
          {
            dictCode: '6',
            dictValue: '外协自供料采购'
          },
          {
            dictCode: '7',
            dictValue: '外协客供料采购'
          }
        ],
        formData: {
          demandType: '1',
          name: '',
          remark: '',
          detailRemoveIds: [],
          materialRemoveIds: []
        },
        formData2: {
          deliveryMethod: 1,
          requireDeliveryTime: '',
          timeList: []
        },
        rules: {
          demandType: [
            {
              required: true,
              message: '请选择需求类型',
              trigger: ['blur', 'change']
            }
          ],
          name: [
            {
              required: true,
              message: '请输入配料计划名称',
              trigger: ['blur', 'change']
            }
          ]
        }
      };
    },
    computed: {
      columns2() {
        return [
          {
            columnKey: 'selection',
            type: 'selection',
            width: 50,
            align: 'center',
            fixed: 'left'
          },
          {
            label: '物料名称',
            prop: 'name',
            align: 'center',
            minWidth: 170,
            fixed: 'left',
            showOverflowTooltip: true
          },

          {
            label: '物料编码',
            prop: 'code',
            align: 'center',
            minWidth: 120,
            fixed: 'left',
            showOverflowTooltip: true
          },
          {
            label: '牌号',
            prop: 'brandNum',
            align: 'center',
            minWidth: 120,
            showOverflowTooltip: true
          },
          {
            prop: 'specification',
            label: '规格',
            align: 'center',
            showOverflowTooltip: true,
            minWidth: 110
          },
          {
            label: '型号',
            prop: 'modelType',
            align: 'center',
            showOverflowTooltip: true
          },
          {
            prop: 'inventoryQuantity',
            label: '库存',
            showOverflowTooltip: true,
            align: 'center'
          },
          // {
          //   prop: 'secureInventory',
          //   label: '安全库存',
          //   showOverflowTooltip: true,
          //   align: 'center'
          // },
          // {
          //   prop: 'lockQuantity',
          //   label: '锁库数量',
          //   showOverflowTooltip: true,
          //   align: 'center'
          // },
          // {
          //   prop: 'inTransitNum',
          //   label: '在途数量',
          //   showOverflowTooltip: true,
          //   align: 'center'
          // },
          // {
          //   prop: 'inTransitOrdersNum',
          //   label: '在途已关联数量',
          //   showOverflowTooltip: true,
          //   align: 'center'
          // },
          // {
          //   prop: 'availableQuantity',
          //   label: '可用数量',
          //   showOverflowTooltip: true,
          //   align: 'center'
          // },
          {
            prop: 'unit',
            label: '计量单位',
            showOverflowTooltip: true,
            align: 'center',
            action: 'unit',
            slot: 'unit'
          },

          {
            label: '需求数量',
            slot: 'demandQuantity',
            action: 'demandQuantity',
            align: 'center',
            minWidth: 120
          },

          // {
          //   label: '采购数量',
          //   slot: 'purchaseQuantity',
          //   action: 'purchaseQuantity',
          //   align: 'center',
          //   minWidth: 120
          // },

          {
            label: '到货方式',
            slot: 'deliveryMethod',
            action: 'deliveryMethod',
            align: 'center',
            minWidth: 140
          },
          {
            label: '采购周期',
            slot: 'purchasingCycle',
            // action: 'purchasingCycle',
            prop: 'purchasingCycle',
            align: 'center',
            minWidth: 160
          },
          {
            label: '要求到货时间',
            slot: 'requireDeliveryTime',
            action: 'requireDeliveryTime',
            align: 'center',
            minWidth: 180
          },

          {
            label: '图纸',
            slot: 'imgUrl',
            action: ' imgUrl',
            align: 'center',
            minWidth: 140
          },

          {
            label: '附件',
            slot: 'files',
            action: ' files',
            align: 'center',
            minWidth: 140
          },
          {
            columnKey: 'action',
            label: '操作',
            width: 110,
            align: 'center',
            slot: 'action'
          }
        ];
      }
    },
    methods: {
      async open(list, planInfo) {
        this.planData = planInfo;
        const name = await getCode('purchase_apply_plan_name');
        this.formData.name = name;
        // this.tableList = list;
        this.materialList = list || [];
        this.buVisible = true;
      },
      handleMethod(row, index) {
        if (row) {
          this.multipleSelection = [];
        }
        this.$refs.timeDialogRef.open(row || {}, index);
      },
      batchUpdateDeliveryMethod() {
        if (this.selection.length == 0) {
          return this.$message.warning('请最少选择一条数据');
        }
        this.formData2 = {
          deliveryMethod: 1,
          requireDeliveryTime: '',
          timeList: []
        };
        this.batchVisible = true;
      },
      cancel() {
        this.buVisible = false;
        this.materialList = [];
        (this.formData = {
          demandType: '1',
          name: '',
          remark: '',
          detailRemoveIds: [],
          materialRemoveIds: []
        }),
          (this.formData2 = {
            deliveryMethod: 1,
            requireDeliveryTime: '',
            timeList: []
          });
      },
      handleCancel() {
        this.batchVisible = false;
      },
      chooseTime(current, timeList, currentIndex) {
        let timeData = JSON.parse(JSON.stringify(timeList));
        if (current && current.categoryId) {
          let data = this.materialList[0];
          this.$set(data, 'timeList', timeData);
          // 单独修改逻辑：直接操作当前物料的 timeList
          // tableList.forEach((item) => {
          //   if (item.id === current.detailId) {
          //     const material = item.materialList[currentIndex];
          //     this.$set(
          //       material,
          //       'timeList',
          //       JSON.parse(JSON.stringify(timeList))
          //     );
          //   }
          // });
        } else if (this.multipleSelection.length > 0) {
          // 批量修改逻辑
          // tableList.forEach((item) => {
          // item.materialList.forEach((material) => {
          this.materialList.forEach((material) => {
            if (
              this.selection.some(
                (selected) => selected.categoryId === material.categoryId
              )
            ) {
              this.$set(
                material,
                'deliveryMethod',
                this.formData2.deliveryMethod
              );
              this.$set(material, 'timeList', timeData);
            }
          });
          // });
          this.$refs.timeDialogRef.handleClose();
          this.batchVisible = false;
        }

        // this.$refs.table.setData([...tableList]);
      },
      handleConfirm() {
        const { deliveryMethod, requireDeliveryTime } = this.formData2;
        // const tableData = this.$refs.table.getData();

        // 创建深拷贝的 timeList 模板（假设当前表单中已填写了分批时间）
        const timeListTemplate = JSON.parse(
          JSON.stringify(this.formData2.timeList)
        );

        // tableData.forEach((item) => {
        //   item.materialList.forEach((m) => {
        this.materialList.forEach((m) => {
          if (
            this.selection.some(
              (selected) => selected.categoryId === m.categoryId
            )
          ) {
            this.$set(m, 'deliveryMethod', deliveryMethod);
            if (deliveryMethod === 1) {
              //一次性到货逻辑
              this.$set(m, 'requireDeliveryTime', requireDeliveryTime);
              this.$set(m, 'timeList', null);
            } else if (deliveryMethod === 2) {
              this.$set(
                m,
                'timeList',
                JSON.parse(JSON.stringify(timeListTemplate))
              );
            }
          }
        });
        // this.$refs.table.setData([...tableData]);
        this.batchVisible = false;
      },
      categorySelect(row) {
        this.$refs.productRefs.open(this.materialList, {});
        // this.$refs.productRefs.open(row.materialList, row, this.type);
      },
      chooseModal(data) {
        let list = data.map((el) => {
          el.isDel = true;
          return el;
        });
        this.materialList.push(...list);
      },
      remove(row, index) {
        this.materialList.splice(index, 1);
        // this.formData.detailRemoveIds.push(row.id);
        // let _arr = this.$refs.table.getData() || [];
        // _arr.splice(index, 1);
        // this.$refs.table.setData([..._arr]);
      },
      confirm() {
        this.$refs.formRef.validate(async (value) => {
          if (value) {
            let params = {};
            if (this.orderType == 2) {
              params = this.planDataS();
            } else {
              params = this.orderData();
            }
            params['type'] = 1;
            params.baitingType = 2;
            params.sourceType = 2;
            params.orderType = this.orderType;

            // console.log(params,'params 333');
            // return
            await save(params);
            this.$message.success('保存成功！');
            this.$emit('success');
            this.cancel();
          }
        });
      },
      orderData() {
        let data = JSON.parse(JSON.stringify(this.planData));
        data.salesOrderCode = data.code;
        data.salesOrderId = data.id;
        let salesList = data.salesOrderSimpleInfoList;
        if (salesList && salesList.length > 0) {
          data.salesOrderCode = salesList[0].salesOrderCode;
          data.salesOrderId = salesList[0].salesOrderId;
        }
        delete data.code;
        delete data.id;
        delete data.salesCode;
        delete data.salesOrderSimpleInfoList;
        let formData = JSON.parse(JSON.stringify(this.formData));
        data.materialList = this.materialList.map((el) => {
          delete el.id;
          return el;
        });
        formData['salesOrderList'] = [data];
        return formData;
      },
      planDataS() {
        let data = JSON.parse(JSON.stringify(this.planData));
        data.producePlanCode = data.code;
        data.producePlanId = data.id;
        let salesList = data.salesOrderSimpleInfoList;
        if (salesList && salesList.length > 0) {
          data.salesOrderCode = salesList[0].salesOrderCode;
          data.salesOrderId = salesList[0].salesOrderId;
        }
        delete data.code;
        delete data.id;
        delete data.salesCode;
        delete data.salesOrderSimpleInfoList;
        let formData = JSON.parse(JSON.stringify(this.formData));
        data.materialList = this.materialList.map((el) => {
          delete el.id;
          return el;
        });
        formData['salesOrderList'] = [data];
        return formData;
      }
    }
  };
</script>
