<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"
    >
      <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-col
          v-for="item in baseFields"
          :key="item.prop"
          :lg="8"
          :md="12"
          :sm="12"
          :xl="8"
          :xs="12"
        >
          <el-form-item :label="item.label">
            <el-input v-model="form[item.prop]" disabled />
          </el-form-item>
        </el-col>

        <el-col :lg="24" :md="24" :sm="24" :xl="24" :xs="24">
          <el-form-item label="备注：">
            <el-input
              v-model="form.remark"
              type="textarea"
              :rows="2"
            ></el-input>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <ele-pro-table
      ref="table"
      :columns="columns"
      :datasource="form.detailList"
      :selection.sync="selection"
      row-key="id"
      cache-key="entrust_list_data_2026_12"
      :height="tableHeight"
      :pageSize="20"
      @fullscreen-change="fullscreenChange"
    >
      <template #quantity="{ row }">
        <el-input v-model="row.quantity" @input="quantityInput(row)">
          <template slot="append">{{ row.measuringUnit }}</template>
        </el-input>
      </template>

      <template #componentAttribute="{ row }">
        <el-tag
          size="small"
          v-if="row.componentAttribute"
          :key="`component-${row.categoryId}`"
        >
          {{ componentAttributeMap[row.componentAttribute] || '' }}
        </el-tag>
      </template>

      <template #attributeType="{ row }">
        <el-tag
          type="success"
          size="small"
          v-if="row.attributeType"
          :key="`attribute-${row.categoryId}`"
        >
          {{ attributeTypeMap[row.attributeType] || '' }}
        </el-tag>
      </template>

      <template #produceType="{ row }">
        <el-tag
          type="warning"
          size="small"
          v-if="row.produceType"
          :key="`produce-${row.categoryId}`"
        >
          {{ produceTypeMap[row.produceType] || '' }}
        </el-tag>
      </template>

      <template #weight="{ row }">
        <span>{{ row.weight }}{{ row.weightUnit }}</span>
      </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>
  </ele-modal>
</template>

<script>
  import {
    savePickingOrder,
    saveBlankingOrder,
    saveReturnOrder
  } from '@/api/requirementListPlan';
  const COMPONENT_ATTRIBUTE_MAP = {
    1: '自制件',
    2: '采购件',
    3: '外协件',
    4: '受托件'
  };

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

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

  const ORDER_TYPE_CONFIG = {
    1: {
      title: '新增下料单',
      loadingText: '下料中...',
      successText: '下料成功',
      api: saveBlankingOrder
    },
    2: {
      title: '新增领料单',
      loadingText: '领料中...',
      successText: '领料成功',
      api: savePickingOrder
    },
    3: {
      title: '新增退料单',
      loadingText: '退料中...',
      successText: '退料成功',
      api: saveReturnOrder
    }
  };

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

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

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

        baseFields: [
          { label: '计划编号：', prop: 'planCode' },
          { label: '批次号：', prop: 'batchNo' },
          { label: '编码：', prop: 'categoryCode' },
          { label: '名称：', prop: 'categoryName' },
          { label: '零部件图号：', prop: 'imgCode' },
          { label: '需求订单号：', prop: 'code' },
          { label: '顶级产品编号：', prop: 'topCategoryCode' },
          { label: '顶级产品名称：', prop: 'topCategoryName' }
        ]
      };
    },

    computed: {
      columns() {
        return [
          {
            columnKey: 'selection',
            type: 'selection',
            width: 45,
            align: 'center',
            fixed: 'left'
          },
          {
            columnKey: 'index',
            label: '序号',
            type: 'index',
            width: 55,
            align: 'center',
            showOverflowTooltip: true,
            fixed: 'left'
          },
          {
            prop: 'categoryLevelName',
            label: '物料分类',
            width: 100,
            align: 'center',
            showOverflowTooltip: true
          },
          {
            prop: 'componentAttribute',
            label: '属性类型',
            width: 100,
            align: 'center',
            showOverflowTooltip: true,
            slot: 'componentAttribute'
          },
          {
            prop: 'attributeType',
            label: '存货类型',
            width: 100,
            align: 'center',
            showOverflowTooltip: true,
            slot: 'attributeType'
          },
          {
            prop: 'produceType',
            label: '生产类型',
            width: 100,
            align: 'center',
            showOverflowTooltip: true,
            slot: 'produceType'
          },
          {
            prop: 'categoryCode',
            label: '物料编码',
            width: 100,
            align: 'center',
            showOverflowTooltip: true
          },
          {
            prop: 'categoryName',
            label: '物料名称',
            width: 100,
            align: 'center',
            showOverflowTooltip: true
          },
          {
            prop: 'modelType',
            label: '型号',
            width: 100,
            align: 'center',
            showOverflowTooltip: true
          },
          {
            prop: 'specification',
            label: '规格',
            width: 100,
            align: 'center',
            showOverflowTooltip: true
          },
          {
            prop: 'quantity',
            label: '数量',
            width: 150,
            align: 'center',
            showOverflowTooltip: true,
            slot: 'quantity'
          },
          // {
          //   prop: 'availableCountBase',
          //   label: '计量库存数量',
          //   width: 200,
          //   align: 'center',
          //   showOverflowTooltip: true,
          //   slot: 'availableCountBase'
          // },

          // {
          //   prop: 'warehouseIdList',
          //   label: '领料仓库',
          //   width: 200,
          //   align: 'center',
          //   showOverflowTooltip: true,
          //   slot: 'warehouseIdList'
          // },

          {
            prop: 'brandNum',
            label: '牌号',
            width: 100,
            align: 'center',
            showOverflowTooltip: true
          },
          {
            prop: 'weight',
            slot: 'weight',
            label: '重量',
            width: 100,
            align: 'center',
            showOverflowTooltip: true
          },
          {
            prop: 'createUserName',
            label: '创建人',
            width: 100,
            align: 'center',
            showOverflowTooltip: true
          },
          {
            prop: 'createTime',
            label: '创建时间',
            width: 100,
            align: 'center',
            showOverflowTooltip: true
          }
        ];
      }
    },

    methods: {
      async open(item) {
        const config = ORDER_TYPE_CONFIG[item.type] || {};
        this.visible = true;
        this.title = config.title || '';
        this.form = item;
      },

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

      quantityInput(row) {
        let val = row.quantity;

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

        const firstDot = val.indexOf('.');
        if (firstDot !== -1) {
          val =
            val.slice(0, firstDot + 1) +
            val.slice(firstDot + 1).replace(/\./g, '');
        }

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

        if (val.length > 1 && val.startsWith('0') && !val.startsWith('0.')) {
          val = val.replace(/^0+/, '');
        }

        const num = Number(val);
        if (Number.isNaN(num)) {
          row.quantity = '';
          return;
        }

        if (this.form.type != 3) {
          if (
            row.unPickQuantity != null &&
            Number(val) > Number(row.unPickQuantity)
          ) {
            this.$message.warning('数量不能大于未领料数量');
            val = row.unPickQuantity;
          }
        } else {
          if (
            row.oddmentsQuantity != null &&
            Number(val) > Number(row.oddmentsQuantity)
          ) {
            this.$message.warning('数量不能大于余料数量');
            val = row.oddmentsQuantity;
          }
        }

        row.quantity = val;
      },

      changeWarehouse() {},

      async handleOk() {
        const config = ORDER_TYPE_CONFIG[this.form.type];
        if (!config) {
          this.$message.error('未知单据类型');
          return;
        }

        const loading = this.$loading({
          lock: true,
          fullscreen: true,
          text: config.loadingText
        });

        try {
          const detailList = this.form.detailList.map((item) => ({
            ...item,
            id: undefined
          }));

          await config.api({
            ...this.form,
            detailList,
            materialRequirements: this.form.code
          });

          this.$message.success(config.successText);
          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)';
      }
    }
  };
</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>
