<template>
  <ele-modal
    width="1160px"
    :visible="visible"
    v-if="visible"
    :append-to-body="true"
    :close-on-click-modal="false"
    custom-class="ele-dialog-form"
    title="物料BOM"
    @update:visible="updateVisible"
  >
    <el-form ref="form" :model="form" :rules="rules" label-width="120px">
      <header-title title="物料BOM"> </header-title>

      <el-row>
        <el-col :span="8">
          <el-form-item label="BOM编码:" prop="code">
            <el-input v-model="form.code" disabled />
          </el-form-item>
        </el-col>

        <el-col :span="8">
          <el-form-item label="BOM名称:" prop="name">
            <el-input placeholder="请输入BOM名称" v-model="form.name" />
          </el-form-item>
        </el-col>

        <el-col :span="8">
          <el-form-item label="版本号:" prop="version">
            <el-input placeholder="请输入BOM版本号" v-model="form.version" />
          </el-form-item>
        </el-col>

        <el-col :span="8">
          <el-form-item label="状态:" prop="status">
            <el-select v-model="form.status" placeholder="" filterable>
              <el-option
                v-for="item in statusList"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>

        <el-col :span="8">
          <el-form-item label="所属工厂" prop="factoryId">
            <factorySelect v-model="form.factoryId" />
          </el-form-item>
        </el-col>

        <el-col :span="8">
          <el-form-item label="基本数量" prop="baseCount">
            <el-row>
              <el-col :span="12">
                <el-input placeholder="请输入" v-model.number="form.baseCount">
                </el-input
              ></el-col>
              <el-col :span="2">&nbsp;</el-col>
              <el-col :span="10">
                <DictSelection
                  dictName="计量单位"
                  v-model="form.baseCountUnit"
                />
              </el-col>
            </el-row>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <div class="ele-body">
          <ele-pro-table
            ref="table"
            :columns="columns"
            :datasource="tableData"
            height="calc(100vh - 550px)"
            :need-page="false"
          >
            <!-- 表头工具栏 -->
            <template v-slot:toolbar>
              <el-button type="primary" @click="add">添加</el-button>
            </template>
            <template v-slot:action="{ row, $index }">
              <el-link type="primary" @click="handleDel(row, $index)"
                >删除</el-link
              >
            </template>
            <template v-slot:subCode="{ row }">
              <el-input v-model="row.subCode" placeholder="请输入"></el-input>
            </template>

            <template v-slot:isReworkBom="{ row }">
              <el-select v-model="row.isReworkBom">
                <el-option
                  v-for="item in isReworkBomList"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                >
                </el-option>
              </el-select>
            </template>

            <template v-slot:unit="{ row }">
              <DictSelection
                dictName="计量单位"
                v-model="row.unit"
              ></DictSelection>
            </template>

            <template v-slot:count="{ row }">
              <el-input
                v-model="row.count"
                placeholder="请输入"
                @input="
                  (value) =>
                    (row.count = value.replace(
                      /^(-)*(\d+)\.(\d\d\d\d\d\d).*$/,
                      '$1$2.$3'
                    ))
                "
              ></el-input>
            </template>

            <template v-slot:categoryName="{ row, $index }">
              <el-input
                :value="row.categoryName"
                placeholder="请选择"
                @click.native="categorySelect(row, $index)"
              ></el-input>
            </template>

            <template v-slot:bomArtFiles="{ row }">
              <fileUpload
                v-model="row.bomArtFiles"
                module="main"
                :showLib="false"
                :limit="5"
              />
              <div v-if="row.bomArtFiles && row.bomArtFiles?.length">
                <el-link
                  v-for="link in row.bomArtFiles"
                  :key="link.id"
                  type="primary"
                  :underline="false"
                  @click="downloadFile(link)"
                >
                  {{ link.name }}</el-link
                >
              </div>
            </template>

            <template v-slot:remark="{ row }">
              <el-input v-model="row.remark" placeholder="请输入"></el-input>
            </template>
          </ele-pro-table>
        </div>
      </el-row>

      <el-row class="rx-cc">
        <el-button
          type="primary"
          size="small"
          class="ele-btn-icon"
          @click="save"
        >
          保存
        </el-button>
      </el-row>
    </el-form>
    <ProductModal ref="productRefs" @changeProduct="determineChoose" />
  </ele-modal>
</template>

<script>
  import factorySelect from '@/components/CommomSelect/factory-select.vue';
  import { pageList } from '@/api/technology/version/version.js';
  import { getCode } from '@/api/codeManagement/index.js';
  import { bomSave, bomUpdate } from '@/api/material/BOM';
  import ProductModal from '@/components/select/bom/ProductModal.vue';
  import fileUpload from '@/components/upload/fileUpload';
  import { getFile } from '@/api/system/file';
  export default {
    components: {
      factorySelect,
      ProductModal,
      fileUpload
    },
    props: {
      // 弹窗是否打开
      visible: Boolean,
      // 修改回显的数据
      categoryId: [String, Number],
      data: Object,
      taskId: [String, Number]
    },
    data() {
      var baseCountVa = (rule, value, callback) => {
        if (value == '') {
          callback(new Error('请输入基本数量'));
        } else if (this.form.baseCountUnit == '') {
          callback(new Error('请选择基本数量单位'));
        } else {
          callback();
        }
      };

      const defaultForm = {
        id: null,
        code: '',
        name: '',
        version: '1.0',
        factoryId: '',
        type: 0,
        status: '',
        isReworkBom: 0,
        baseCount: '',
        baseCountUnit: '',
        taskId: ''
      };
      return {
        defaultForm,
        // 表单数据
        form: {
          ...defaultForm
        },

        removeSubBomIdList: [],
        versionList: [],

        // 表单验证规则
        rules: {
          code: [{ required: true, message: '请输入BOM编码', trigger: 'blur' }],

          name: [{ required: true, message: '请输入BOM名称', trigger: 'blur' }],

          version: [
            { required: true, message: '请输入BOM版本号', trigger: 'blur' }
          ],

          status: [
            { required: true, message: '请选择状态', trigger: 'change' }
          ],

          factoryId: [
            { required: true, message: '请输入所属工厂', trigger: 'change' }
          ],

          baseCount: [{ validator: baseCountVa, trigger: 'blur' }]
        },
        columns: [
          {
            type: 'index',
            width: 55,
            align: 'center'
          },
          {
            label: '子项编号',
            prop: 'subCode',
            slot: 'subCode',
            action: 'subCode'
          },
          {
            label: '物料名称',
            prop: 'categoryName',
            slot: 'categoryName',
            action: 'categoryName'
          },
          {
            label: '是否回收料',
            prop: 'isReworkBom',
            slot: 'isReworkBom',
            action: 'isReworkBom'
          },
          {
            label: '物料编码',
            prop: 'categoryCode'
          },
          {
            label: '牌号',
            prop: 'brandNum'
          },
          {
            label: '型号',
            prop: 'modelType'
          },
          {
            label: '数量',
            slot: 'count',
            action: 'count'
          },
          {
            label: '单位',
            slot: 'unit',
            action: 'unit'
          },

          {
            label: '附件',
            slot: 'bomArtFiles',
            action: 'bomArtFiles',
            minWidth: 100
          },

          {
            label: '备注',
            slot: 'remark',
            action: 'remark'
          },

          {
            action: 'action',
            slot: 'action',
            label: '操作'
          }
        ],

        tableData: [],
        statusList: [
          { label: '草稿', value: -1 },
          { label: '失效', value: 0 },
          { label: '生效', value: 1 }
        ],

        isReworkBomList: [
          { label: '否', value: 0 },
          { label: '是', value: 1 }
        ],

        // 提交状态
        loading: false,
        // 是否是修改
        isUpdate: false
      };
    },
    computed: {
      // 是否开启响应式布局
      styleResponsive() {
        return this.$store.state.theme.styleResponsive;
      }
    },
    methods: {
      downloadFile(file) {
        getFile({ objectName: file.storePath }, file.name);
      },

      handleDel(row, index) {
        this.tableData.splice(index, 1);
        if (row?.id) {
          this.removeSubBomIdList.push(row.id);
        }
      },

      add() {
        let subCode = '0010';
        if (this.tableData.length) {
          let max = Math.max(...this.tableData.map((i) => i.subCode)) + 10 + '';

          if (max.length < 4) {
            max = new Array(4 - max.length).fill('0').join('') + max;
          }
          subCode = max.substring(0, max.length - 1) + '0';
        }

        this.tableData.push({
          subCode,
          categoryId: '',
          categoryName: '',
          isReworkBom: 0,
          brandNum: '',
          count: '',
          modelType: '',
          unit: '',
          netWeight: '',
          weightUnit: ''
        });
      },

      async _getCode() {
        const code = await getCode('bom_code');
        this.form.code = code;
      },

      /* 保存编辑 */
      save() {
        this.$refs.form.validate((valid) => {
          if (!valid) {
            return false;
          }

          if (this.tableData.length == 0) {
            this.$message.error('请至少添加一条物料');
            return;
          }

          let boolen = this.tableData.every((item) => item.categoryName);
          if (!boolen) {
            this.$message.error('请完善物料名称！');
            return false;
          }

          if (!this.isUpdate) {
            delete this.form.id;
            this.form['taskId'] = this.taskId;
          }

          const data = {
            ...this.form,
            removeSubBomIdList: this.removeSubBomIdList,
            subDetailList: this.tableData,
            categoryId: this.categoryId
          };

          this.loading = true;

          const saveOrUpdate = this.isUpdate ? bomUpdate : bomSave;
          saveOrUpdate(data)
            .then((msg) => {
              this.loading = false;
              this.$message.success(msg);
              this.$emit('done', this.form['taskId']);
              this.visible = false;
            })
            .catch((e) => {
              this.loading = false;
            });
        });
      },

      categorySelect(row, idx) {
        // 3  type: 物料组
        this.$refs.productRefs.open(row, '选择物料', 3, idx);
      },

      determineChoose(title, row, idx) {
        if (title == '选择物料') {
          this.$set(this.tableData[idx], 'categoryName', row.name);
          this.$set(this.tableData[idx], 'categoryId', row.id);
          this.$set(this.tableData[idx], 'categoryCode', row.code);
          this.$set(this.tableData[idx], 'unit', row.measuringUnit);
          this.$set(this.tableData[idx], 'weightUnit', row.weightUnit);
          this.$set(this.tableData[idx], 'brandNum', row.brandNum);
          this.$set(this.tableData[idx], 'modelType', row.modelType);
        }
      },

      /* 更新visible */
      updateVisible(value) {
        this.$emit('update:visible', value);
      }
    },

    watch: {
      async visible(visible) {
        if (visible) {
          this._getCode();

          this.removeSubBomIdList = [];

          if (this.data) {
            this.tableData = this.data.subDetailList;
            this.$util.assignObject(this.form, {
              ...this.data
            });
            this.isUpdate = true;
          } else {
            this.tableData = [];
            this.isUpdate = false;
          }
        } else {
          this.$refs.form.clearValidate();
          this.form = { ...this.defaultForm };
        }
      }
    }
  };
</script>
