<template>
  <ele-modal
    width="80vw"
    :visible.sync="visible"
    custom-class="ele-dialog-form"
    :before-close="cancel"
    :title="title"
    :maxable="true"
  >
    <el-form
      ref="form"
      :model="form"
      :rules="rules"
      label-position="right"
      label-width="140px"
      v-if="form"
    >
      <el-row :gutter="10" class="basic">
        <el-col :lg="8" :md="12" :sm="12" :xl="8" :xs="12">
          <el-form-item label="计划编号：">
            <el-input v-model="form.planCode" disabled></el-input>
          </el-form-item>
        </el-col>

        <el-col :lg="8" :md="12" :sm="12" :xl="8" :xs="12">
          <el-form-item label="批次号：">
            <el-input v-model="form.batchNo" disabled></el-input>
          </el-form-item>
        </el-col>

        <el-col :lg="8" :md="12" :sm="12" :xl="8" :xs="12">
          <el-form-item label="编码：">
            <el-input v-model="form.categoryCode" disabled></el-input>
          </el-form-item>
        </el-col>

        <el-col :lg="8" :md="12" :sm="12" :xl="8" :xs="12">
          <el-form-item label="名称：">
            <el-input v-model="form.categoryName" disabled></el-input>
          </el-form-item>
        </el-col>

        <el-col :lg="8" :md="12" :sm="12" :xl="8" :xs="12">
          <el-form-item label="零部件图号：">
            <el-input v-model="form.imgCode" disabled></el-input>
          </el-form-item>
        </el-col>

        <el-col :lg="8" :md="12" :sm="12" :xl="8" :xs="12">
          <el-form-item label="需求订单号：">
            <el-input v-model="form.code" disabled></el-input>
          </el-form-item>
        </el-col>

        <el-col :lg="8" :md="12" :sm="12" :xl="8" :xs="12">
          <el-form-item label="顶级产品编号：">
            <el-input v-model="form.topCategoryName" disabled></el-input>
          </el-form-item>
        </el-col>

        <el-col :lg="8" :md="12" :sm="12" :xl="8" :xs="12">
          <el-form-item label="顶级产品名称：">
            <el-input v-model="form.topCategoryName" disabled></el-input>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <ele-pro-table
      ref="table"
      :columns="columns"
      :datasource="borrowList"
      :selection.sync="selection"
      row-key="id"
      cache-key="entrust_list_data_2026_12"
      :height="tableHeight"
      :pageSize="20"
      @fullscreen-change="fullscreenChange"
    >
      <template v-slot:toolbar>
        <div class="toolbar_box">
          <el-button type="primary" size="mini" @click="handleAdd"
            >新增</el-button
          >
        </div>
      </template>
      <template #quantity="{ row }">
        <span
          >{{ row.feedingControlQty ? row.feedingControlQty : 0 }}/{{
            row.quantity ? row.quantity : 0
          }}</span
        >
      </template>

      <template #componentAttribute="{ row }">
        <el-tag size="small">{{
          componentAttributeMap[row.componentAttribute]
        }}</el-tag>
      </template>

      <template #attributeType="{ row }">
        <el-tag type="success" size="small">{{
          attributeTypeMap[row.attributeType]
        }}</el-tag>
      </template>

      <template #produceType="{ row }">
        <el-tag type="warning" size="small">{{
          produceTypeMap[row.produceType]
        }}</el-tag></template
      >

      <template #remark="{ row }">
        <el-input v-model="row.remark"></el-input>
      </template>
    </ele-pro-table>

    <div class="btns">
      <el-button type="primary" size="small" @click="handleOk">确认</el-button>
      <el-button size="small" @click="cancel">取消</el-button>
    </div>

    <picking-list
      ref="pickingListRef"
      :isType="isType"
      @allSelection="allSelection"
    />
  </ele-modal>
</template>

<script>
  import { saveBorrowOrder } from '@/api/requirementListPlan';
  import pickingList from './pickingList.vue';

  const COMPONENT_ATTRIBUTE_MAP = {
    1: '自制件',
    2: '采购件',
    3: '外协件',
    4: '受托件'
  };

  const ATTRIBUTE_TYPE_MAP = {
    1: '总装',
    2: '部装',
    3: '零件',
    4: '原材料'
  };

  const PRODUCE_TYPE_MAP = {
    1: '加工',
    2: '装配',
    3: '下料'
  };

  export default {
    components: { pickingList },
    data() {
      return {
        form: {},
        rules: {},
        id: '',
        submitting: false,

        tableHeight: 'calc(100vh - 595px)',
        detailList: [],
        selection: [],
        visible: false,
        title: '',
        isType: 'feed',
        borrowList: [],

        componentAttributeMap: COMPONENT_ATTRIBUTE_MAP,
        attributeTypeMap: ATTRIBUTE_TYPE_MAP,
        produceTypeMap: PRODUCE_TYPE_MAP
      };
    },

    computed: {
      columns() {
        return [
          {
            width: 45,
            type: 'selection',
            columnKey: 'selection',
            align: 'center',
            reserveSelection: true
          },
          {
            columnKey: 'index',
            label: '序号',
            type: 'index',
            width: 50,
            align: 'center'
          },
          {
            prop: 'categoryCode',
            label: '物品编码',
            slot: 'categoryCode',
            showOverflowTooltip: true
          },

          {
            prop: 'code',
            label: '编码',
            showOverflowTooltip: true
          },

          {
            prop: 'codeNumber',
            label: '编号',
            showOverflowTooltip: true
          },
          {
            prop: 'name',
            label: '名称',
            showOverflowTooltip: true
          },
          {
            prop: 'brandNum',
            label: '牌号',
            showOverflowTooltip: true
          },
          {
            prop: 'specification',
            label: '规格',
            showOverflowTooltip: true
          },
          {
            prop: 'modelType',
            label: '型号',
            showOverflowTooltip: true
          },

          {
            prop: 'batchNo',
            label: '批次号',
            align: 'center'
          },

          {
            prop: 'availableCountBase',
            label: '计量库存数量',
            sortable: 'custom',
            slot: 'availableCountBase',
            showOverflowTooltip: true,
            width: 130,
            align: 'center'
          },

          ...([1, 23, 8].includes(Number(this.rootCategoryLevelId))
            ? [
                {
                  prop: 'packingCountBase',
                  label: '包装库存',
                  slot: 'packingCountBase',
                  showOverflowTooltip: true
                }
              ]
            : []),

          {
            prop: 'weight',
            label: '重量',
            showOverflowTooltip: true,
            slot: 'weight'
          },

          {
            prop: 'expirationDate',
            slot: 'expirationDate',
            label: '库存保质期',
            width: 100
          },
          {
            prop: 'expirationTime',
            label: '周期倒计时',
            showOverflowTooltip: true,
            width: 100
          },
          {
            prop: 'qualityResult',
            slot: 'qualityResult',
            label: '质检结果',
            showOverflowTooltip: true,
            width: 100
          },
          {
            prop: 'qualityStatus',
            slot: 'qualityStatus',
            label: '质检状态',
            showOverflowTooltip: true,
            width: 100
          },
          ...(this.isType != 'feed'
            ? [
                {
                  prop: 'pathName',
                  width: 230,
                  label: '仓库',
                  showOverflowTooltip: true
                }
              ]
            : []),

          ...(this.rootCategoryLevelId == '4'
            ? [
                {
                  prop: 'workstationName',
                  label: '工位',
                  showOverflowTooltip: true
                },

                {
                  prop: 'runStatus',
                  label: '状态',
                  slot: 'runStatus',
                  showOverflowTooltip: true
                }
              ]
            : []),

          ...(this.rootCategoryLevelId == '8'
            ? [
                {
                  prop: 'extInfo.slotNum',
                  label: '槽数',
                  showOverflowTooltip: true
                }
              ]
            : []),

          ...(this.rootCategoryLevelId == '11'
            ? [
                {
                  prop: 'status',
                  label: '状态',
                  slot: 'status',
                  showOverflowTooltip: true
                },

                {
                  prop: 'region',
                  label: '位置',
                  showOverflowTooltip: true
                }
              ]
            : [])
        ];
      }
    },

    methods: {
      open(item) {
        this.visible = true;
        this.title = '新增领用单';
        this.form = item;
      },

      handleAdd() {
        this.$refs.pickingListRef.open(this.borrowList);
      },

      cancel() {
        this.visible = false;
      },

      async handleOk() {
        const loading = this.$loading({
          lock: true,
          fullscreen: true,
          text: '领用中...'
        });

        this.borrowList = this.borrowList.map((item) => {
          item.id = undefined;
          return item;
        });

        try {
          const api = saveBorrowOrder;
          await api({
            ...this.form,
            detailList: this.borrowList,
            materialRequirements: this.form ? this.form.code : undefined
          });
          this.$message.success('领用成功');
          this.$emit('refresh');
          this.visible = false;
        } catch (e) {
          console.error(e);
          this.$message.error('操作失败，请稍后重试');
        } finally {
          loading.close();
        }
      },

      fullscreenChange(fullscreen) {
        this.tableHeight = fullscreen
          ? 'calc(100vh - 120px)'
          : 'calc(100vh - 595px)';
      },
      allSelection(selection) {
        this.borrowList = selection.map((item) => {
          return {
            ...item,
            substanceId: item.id,
            substanceCode: item.code
          };
        });
      }
    }
  };
</script>

<style scoped>
  ::v-deep .el-form-item {
    margin-bottom: 15px !important;
  }

  .btns {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
    gap: 10px;
  }
</style>
