<template>
  <ele-modal
    title="新建领料单"
    :visible.sync="visible"
    v-if="visible"
    :before-close="handleClose"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    append-to-body
    :maxable="true"
    width="95%"
  >
    <div>
      <el-form :model="pickForm" ref="pickForm">
        <el-row :gutter="24">
          <el-col :span="6">
            <el-form-item label="领料单编号" prop="pickCode" label-width="90px">
              <el-input v-model="pickForm.pickCode" disabled=""></el-input>
            </el-form-item>
          </el-col>

          <el-col :span="6">
            <el-form-item label="领料单名称" prop="pickName" label-width="90px">
              <el-input v-model="pickForm.pickName"></el-input>
            </el-form-item>
          </el-col>

          <el-col :span="6">
            <el-button type="primary" @click="selectOrder">选择工单</el-button>
          </el-col>
        </el-row>
      </el-form>

      <div v-for="(item, idx) in workList" :key="idx">
        <el-form
          :ref="`form22${idx}`"
          :model="{ pickList: item }"
          :rules="tableRules"
          size="mini"
          label-position="left"
        >
          <div class="tableZ_box">
            <div class="row">
              <div class="col">
                <div class="name">生产工单号</div>
                <div class="content">{{ item.code }}</div>
              </div>
              <div class="col">
                <div class="name">产品编码</div>
                <div class="content">{{ item.productCode }}</div>
              </div>
              <div class="col">
                <div class="name">产品名称</div>
                <div class="content">{{ item.productName }}</div>
              </div>
              <div class="col">
                <div class="name">批次号</div>
                <div class="content">{{ item.batchNo }}</div>
              </div>
              <div class="col">
                <div class="name">型号</div>
                <div class="content">{{ item.model }}</div>
              </div>

              <div class="col">
                <div class="name">规格</div>
                <div class="content">{{ item.specification }}</div>
              </div>

              <div class="col">
                <div class="name">颜色</div>
                <div class="content">{{ item.colorKey }}</div>
              </div>
              <div class="col pd6">
                <el-button
                  type="primary"
                  size="mini"
                  @click="openPicking(item.id, item)"
                  >新增</el-button
                >
              </div>
            </div>
          </div>

          <div>
            <el-table
              :ref="`form222${idx}`"
              class="table_content"
              :max-height="300"
              :data="item.pickList"
              tooltip-effect="dark"
              style="width: 100%"
              stripe
              border
            >
              <el-table-column label="序号" type="index" width="60">
                <template slot-scope="{ row, $index }">
                  {{ $index + 1 }}
                </template>
              </el-table-column>

              <el-table-column
                label="类型"
                prop="rootCategoryLevelId"
                width="80"
              >
                <template slot-scope="{ row, $index }">
                  <el-tag size="mini">{{
                    typeName[Number(row.rootCategoryLevelId)]
                  }}</el-tag>
                </template>
              </el-table-column>

              <el-table-column
                label="编码"
                prop="assetCode"
                show-overflow-tooltip
              >
                <template slot-scope="{ row, $index }">
                  <span
                    v-if="
                      Object.prototype.hasOwnProperty.call(row, 'isBom') &&
                      row.isBom == 1
                    "
                    style="color: #faad14"
                  >
                    {{ row.categoryCode }}
                  </span>
                  <span>
                    {{
                      row.rootCategoryLevelId == 4 ? row.codeNumber : row.code
                    }}</span
                  >
                </template>
              </el-table-column>

              <el-table-column label="名称" prop="name" show-overflow-tooltip>
                <template slot-scope="{ row, $index }">
                  <span
                    v-if="
                      Object.prototype.hasOwnProperty.call(row, 'isBom') &&
                      row.isBom == 1
                    "
                  >
                    {{ row.categoryName }}
                  </span>
                  <span> {{ row.name }}</span>
                </template>
              </el-table-column>
              <el-table-column
                label="型号"
                prop="modelType"
                show-overflow-tooltip
              >
              </el-table-column>
              <el-table-column
                label="规格"
                prop="specification"
                show-overflow-tooltip
              >
              </el-table-column>
              <el-table-column
                label="批次号"
                prop="batchNo"
                show-overflow-tooltip
              >
              </el-table-column>

              <el-table-column label="数量" prop="demandQuantity" width="160">
                <template slot-scope="{ row, $index }">
                  <el-form-item>
                    <el-input
                      v-model="row.demandQuantity"
                      @input="changeInput(row, $index, idx)"
                      size="mini"
                      style="width: 120px"
                    >
                      <template slot="append">{{ row.measuringUnit }}</template>
                    </el-input>
                  </el-form-item>
                </template>
              </el-table-column>

              <el-table-column
                label="计量库存数量"
                prop="availableCountBase"
                width="320"
                show-overflow-tooltip
              >
                <template slot-scope="{ row, $index }">
                  <div v-for="it of row.warehouseList">
                    <span
                      v-if="it.availableCountBase != '0'"
                      style="cursor: pointer"
                      >{{ it.name ? it.name : it.warehouse_name }}库存数：<span
                        style="color: green"
                        >{{ it.availableCountBase }}</span
                      >{{ row.measuringUnit }}，
                      <span v-if="it.lockQuantity || it.lockQuantity == 0"
                        >锁库数：<span style="color: red">{{
                          it.lockQuantity
                        }}</span
                        >{{ row.measuringUnit }}
                      </span></span
                    >
                  </div>
                </template>
              </el-table-column>

              <el-table-column
                label="领料仓库"
                prop="warehouseId"
                width="180"
                show-overflow-tooltip
              >
                <template slot-scope="{ row, $index }">
                  <div
                    v-if="
                      Object.prototype.hasOwnProperty.call(row, 'isBom') &&
                      row.isBom == 1
                    "
                  >
                    <el-select
                      v-model="row.warehouseIdList"
                      placeholder="请选择"
                      filterable
                      multiple
                      @change="changeWarehouse(row, $index)"
                    >
                      <el-option
                        v-for="item in row.warehouseList"
                        :label="item.name"
                        :value="item.id"
                        :key="item.id"
                      >
                      </el-option>
                    </el-select>
                  </div>

                  <div v-else>
                    <el-select
                      v-model="row.warehouseIdList"
                      placeholder="请选择"
                      filterable
                      multiple
                      @change="changeWarehouse(row, $index)"
                    >
                      <el-option
                        v-for="item in row.warehouseList"
                        :label="item.warehouse_name"
                        :value="item.warehouse_id"
                        :key="item.warehouse_id"
                      >
                      </el-option>
                    </el-select>
                  </div>
                </template>
              </el-table-column>

              <el-table-column label="操作" fixed="right" width="100px">
                <template slot-scope="{ $index, row }">
                  <el-link type="danger" @click="removeItem(idx, $index)"
                    >删除</el-link
                  >
                </template>
              </el-table-column>
            </el-table>
          </div>
        </el-form>
      </div>
    </div>

    <template slot="footer">
      <el-button size="mini" @click="handleClose">取 消</el-button>
      <el-button size="mini" type="primary" @click="save()">确 定</el-button>
    </template>

    <pickingList
      isType="pick"
      ref="pickingListRef"
      @allSelection="allSelection"
    ></pickingList>

    <produceOrder
      v-if="orderShow"
      @close="orderShow = false"
      @workSelect="workSelect"
    ></produceOrder>
  </ele-modal>
</template>

<script>
  import pickingList from '@/views/produce/components/picking/newPickingList.vue';
  import { workorderList, getCode } from '@/api/produce/workOrder';
  import produceOrder from './produceOrder.vue';

  import { typeName } from '@/views/produce/components/common.js';
  import { batchSave } from '@/api/produce/picking';

  import { listTask } from '@/api/produce/index';

  export default {
    components: {
      pickingList,
      produceOrder
    },
    props: {},
    data() {
      return {
        visible: true,

        workList: [],

        rules: {},

        pickForm: {
          pickCode: null,
          pickName: null
        },

        typeName,

        tableRules: {},

        produceTaskList: [],

        orderShow: false
      };
    },
    computed: {
      taskObj() {
        return this.$store.state.user.taskObj;
      }
    },

    watch: {},
    methods: {
      getTaskList() {
        listTask().then((res) => {
          this.produceTaskList = res;
        });
      },

      getList(ids, taskId) {
        const param = { ids, taskId };

        workorderList(param).then((res) => {
          console.log(res, 'resres');
          this.workList = res.map((item) => {
            // 处理 pickList 并统一 warehouse 字段
            const pickList = item.bomDetailDTOS.map((it) => {
              const warehouseList = (it.warehouseList || []).map((wh) => ({
                ...wh,
                warehouse_id: wh.id,
                warehouse_name: wh.name
              }));

              return {
                ...it,
                warehouseIdList: it.warehouseId ? [it.warehouseId] : [],
                warehouseList
              };
            });

            return {
              ...item,
              pickList,
              bomDetailDTOS: [] // 清空原 bomDetailDTOS
            };
          });
        });
      },

      async getOrderCode() {
        this.pickForm.pickCode = await getCode('pick_order_code');
      },

      removeItem(idx, index) {
        this.workList[idx].pickList.splice(index, 1);
      },

      handleClose() {
        this.$emit('close', false);
      },

      openPicking(id, item) {
        this.$refs.pickingListRef.open(id, item);
      },

      allSelection(id, list) {
        // this.workList.forEach((e) => {
        //   if (e.id == id) {
        //     e.pickList = list;
        //     this.$forceUpdate();
        //   }
        // });
        console.log(id, list);
        list.forEach((item) => {
          item.code = item.categoryCode;
          item.name = item.categoryName;
          item.modelType = item.modelType ? item.modelType : item.categoryModel;
          item.measuringUnit = item.measuringUnit
            ? item.measuringUnit
            : item.measureUnit;
          item.unit = item.unit ? item.unit : item.measureUnit;
        });

        this.workList.forEach((e) => {
          if (e.id == id) {
            const newData = [];
            if (list.length != 0) {
              list.forEach((it) => {
                newData.push(this.deepCopy(it));
              });
            }
            // e.pickList = list;
            e.pickList = newData;
            this.$forceUpdate();
          }
        });
      },

      deepCopy(obj, hash = new WeakMap()) {
        if (obj === null) return null;
        if (obj instanceof Date) return new Date(obj);
        if (obj instanceof RegExp) return new RegExp(obj);
        if (typeof obj !== 'object' && typeof obj !== 'function') return obj;
        if (hash.has(obj)) return hash.get(obj);

        const result = Array.isArray(obj) ? [] : {};
        hash.set(obj, result);

        return Object.keys(obj).reduce((acc, key) => {
          acc[key] = this.deepCopy(obj[key], hash);
          return acc;
        }, result);
      },

      save() {
        if (this.workList.length > 0) {
          let bol;
          let _i;
          bol = this.workList.every((e, i) => {
            _i = i;
            return (
              Object.prototype.hasOwnProperty.call(e, 'pickList') &&
              e.pickList.length > 0
            );
          });

          if (!bol) {
            this.$message.warning(
              `生成工单${this.workList[_i].code}领料不能为空`
            );
            return false;
          }
        }

        if (this.workList.length > 0) {
          let name;
          let bol2;
          let _i;

          this.workList.forEach((e, i) => {
            _i = i;
            console.log(e.pickList);
            bol2 = e.pickList.every((y) => {
              name = y.name;
              return (
                Object.prototype.hasOwnProperty.call(y, 'demandQuantity') &&
                Number(y.demandQuantity) > 0
              );
            });
          });

          if (!bol2) {
            this.$message.warning(
              `${this.workList[_i].code}的${name}数量不能为空`
            );
            return false;
          }
        }

        let _arr = [];
        _arr = this.workList.map((m) => {
          m.instanceList = [];
          m.bomDetailDTOSList = [];
          m.pickList.forEach((e) => {
            if (
              Object.prototype.hasOwnProperty.call(e, 'isBom') &&
              e.isBom == 1
            ) {
              m.bomDetailDTOSList.push(e);
            } else {
              m.instanceList.push(e);
            }
          });
          m.workOrderId = m.id;
          delete m.id;

          return {
            ...m
          };
        });

        let param = {
          allPickList: _arr,
          pickName: this.pickForm.pickName,
          pickCode: this.pickForm.pickCode
        };

        batchSave(param).then((res) => {
          this.$message.success('领料成功');
          this.$emit('close', true);
        });
      },

      selectOrder() {
        this.orderShow = true;
      },

      workSelect(ids, taskId) {
        console.log(ids, taskId, 'ids, taskId');
        this.getList(ids, taskId);

        this.orderShow = false;
      },
      changeWarehouse(item, index) {},

      changeInput(item, index, idx) {
        const pickItem = this.workList[idx].pickList[index];

        let value = String(item.demandQuantity ?? '');

        value = value.replace(/[^\d.]/g, '');

        value = value
          .replace(/\.{2,}/g, '.')
          .replace('.', '$#$')
          .replace(/\./g, '')
          .replace('$#$', '.');

        if (value.includes('.')) {
          const [intPart, decPart] = value.split('.');
          value = `${intPart}.${decPart.slice(0, 4)}`;
        }

        this.$set(pickItem, 'demandQuantity', value);

        const demandQty = Number(value);
        const maxQty = item.warehouseList.reduce((sum, cur) => {
          return sum + Number(cur.availableCountBase || 0);
        }, 0);

        if (!demandQty) {
          this.$set(pickItem, 'warehouseIdList', []);
          return;
        }

        if (demandQty >= maxQty) {
          this.$set(pickItem, 'demandQuantity', maxQty);

          this.$set(
            pickItem,
            'warehouseIdList',
            item.warehouseList.map((w) => w.warehouse_id)
          );
          return;
        }

        let total = 0;
        const idsList = [];

        for (const w of item.warehouseList) {
          total += Number(w.availableCountBase) || 0;
          idsList.push(w.warehouse_id);

          if (total >= demandQty) break;
        }

        this.$set(pickItem, 'warehouseIdList', idsList);
      }

      // changeInput(item, index, idx) {
      //   if (Number(item.demandQuantity) >= Number(item.availableCountBase)) {
      //     this.$set(
      //       this.workList[idx].pickList[index],
      //       'demandQuantity',
      //       Number(item.availableCountBase)
      //     );
      //     const idsList = [];
      //     item.warehouseList.forEach((it) => {
      //       idsList.push(it.id);
      //     });
      //     this.$set(
      //       this.workList[idx].pickList[index],
      //       'warehouseIdList',
      //       idsList
      //     );
      //   } else if (!Number(item.demandQuantity)) {
      //     this.$set(this.workList[idx].pickList[index], 'warehouseIdList', []);
      //   } else {
      //     const idsList = [];
      //     let totalNum = 0;
      //     for (let i = 0; i < item.warehouseList.length; i++) {
      //       totalNum += Number(item.warehouseList[i].availableCountBase);
      //       if (Number(item.demandQuantity) > totalNum) {
      //         idsList.push(item.warehouseList[i].id);
      //       } else {
      //         idsList.push(item.warehouseList[i].id);
      //         break;
      //       }
      //     }
      //     this.$set(
      //       this.workList[0].pickList[index],
      //       'warehouseIdList',
      //       idsList
      //     );
      //   }
      // }
    },

    created() {
      this.getTaskList();
      this.getOrderCode();
    }
  };
</script>

<style lang="scss" scoped>
  .table_content {
    margin-bottom: 10px;
  }

  .tableZ_box {
    border: 1px solid #e3e5e5;
    margin: 6px 0;

    &:last-child {
      border-bottom: none;
    }

    .row {
      width: 100%;
      display: flex;
    }

    .col {
      width: calc(100% / 5);
      display: flex;
      align-items: center;
      // min-width: 200px;
      min-height: 32px;
      border-bottom: 1px solid #e3e5e5;
      border-right: 1px solid #e3e5e5;

      &:last-child {
        border-right: none;
      }

      .name {
        display: flex;
        align-items: center;
        padding: 4px;
        width: 60px;
        height: 100%;
        background-color: #d0e4d5;
        color: #000;
      }

      .content {
        padding: 4px 6px;
        color: #000;
      }
    }

    .pd6 {
      padding: 0 6px;
    }
  }
</style>

<style>
  :v-deep .el-form-item__error {
    bottom: -6px !important;
  }
</style>
