<template>
  <div class="ele-body">
    <el-card :body-style="{ padding: 0 }">
      <div class="page-container equipment-container">
        <div class="page-title basic-details-title">
          <el-page-header @back="$router.go(-1)">
            <div slot="content" class="pageContent">
              <div>编辑模具信息</div>
            </div>
          </el-page-header>
          <div>
            <el-button size="small" @click="$router.go(-1)">取消</el-button>
            <el-button
              size="small"
              type="primary"
              @click="toSave"
              v-loading="btnLoading"
              >确定</el-button
            >
          </div>
        </div>
        <div class="content">
          <el-form label-width="100px">
            <basicInfoVue ref="basicInfoVueRef" />

            <div class="basic-details-title border-none">
              <span class="border-span">资产信息</span>
            </div>
            <el-descriptions
              title=""
              :column="4"
              size="medium"
              border
              style="edit"
            >
              <el-descriptions-item>
                <template slot="label"> 模具编码 </template>
                <el-form-item label-width="0">
                  <el-input size="small" v-model="info.mouldCode"></el-input>
                </el-form-item>
              </el-descriptions-item>
              <el-descriptions-item>
                <template slot="label"> 固资编码 </template>
                <el-form-item label-width="0">
                  <el-input size="small" v-model="info.fixCode"></el-input>
                </el-form-item>
              </el-descriptions-item>
              <el-descriptions-item>
                <template slot="label"> 编号 </template>
                <el-form-item label-width="0">
                  <el-input size="small" v-model="info.codeNumber"></el-input>
                </el-form-item>
              </el-descriptions-item>
              <el-descriptions-item>
                <template slot="label"> 已冲压次数 </template>
                <el-form-item label-width="0">
                  <el-input size="small" v-model="info.startCyTimes"></el-input>
                </el-form-item>
              </el-descriptions-item>
              <el-descriptions-item>
                <template slot="label"> 权属部门 </template>
                <el-form-item label-width="0">
                  <ele-tree-select
                    clearable
                    :data="treeData"
                    v-model="info.ownershipGroupId"
                    placeholder="请选择"
                    default-expand-all
                    labelKey="name"
                    valueKey="id"
                  />
                </el-form-item>
              </el-descriptions-item>
            </el-descriptions>

            <div class="basic-details-title border-none">
              <span class="border-span">模具信息</span>
            </div>
            <el-descriptions title="" :column="4" size="medium" border>
              <el-descriptions-item>
                <template slot="label"> 收缩系数</template>
                {{
                  categoryMold.shrinkEffictive
                    ? categoryMold.shrinkEffictive + '%'
                    : null
                }}
              </el-descriptions-item>
              <el-descriptions-item>
                <template slot="label"> 芯杆数量 </template>
                {{ categoryMold.coreBarNum }}
              </el-descriptions-item>
              <el-descriptions-item>
                <template slot="label"> 模孔数量</template>
                {{ categoryMold.dieHoleNum }}
              </el-descriptions-item>
              <el-descriptions-item>
                <template slot="label"> 上冲头数量</template>
                {{ categoryMold.upperPunchNum }}
              </el-descriptions-item>
              <el-descriptions-item>
                <template slot="label"> 下冲头数量</template>
                {{ categoryMold.downPunchNum }}
              </el-descriptions-item>

              <el-descriptions-item>
                <template slot="label"> 最大冲压次数</template>
                {{ categoryMold.maxCyTimes }}
              </el-descriptions-item>
              <el-descriptions-item>
                <template slot="label"> 大模体型号 </template>
                {{ categoryMold.maxMoldType }}
              </el-descriptions-item>

              <el-descriptions-item>
                <template slot="label"> 芯棒直径 </template>
                {{ categoryMold.mandrelDiameter }}
              </el-descriptions-item>
            </el-descriptions>

            <div class="basic-details-title border-none">
              <span class="border-span">仓储配置</span>
            </div>
            <el-descriptions title="" :column="4" size="medium" border>
              <el-descriptions-item>
                <template slot="label"> 启用库存预警</template>
                {{ dictType[categoryWms.isWarn] }}
              </el-descriptions-item>
              <el-descriptions-item>
                <template slot="label">允许拆包</template>
                {{ dictType[categoryWms.isUnpack] }}
              </el-descriptions-item>
              <el-descriptions-item>
                <template slot="label">安全库存</template>
                {{ categoryWms.secureInventory }}
              </el-descriptions-item>
              <el-descriptions-item>
                <template slot="label">最小库存</template>
                {{ categoryWms.minInventory }}
              </el-descriptions-item>
              <el-descriptions-item>
                <template slot="label"> 最大库存</template>
                {{ categoryWms.maxInventory }}
              </el-descriptions-item>
              <el-descriptions-item>
                <template slot="label">盘点模式</template>
                {{ dictPd[categoryWms.inventoryMode] }}
              </el-descriptions-item>
              <el-descriptions-item>
                <template slot="label">质保预警参考</template>
                <!-- <DictSelection
                dictName="质保预警参考"
                clearable
                v-model="categoryWms.warrantyWarnRefer"
              >
              </DictSelection> -->
                {{ categoryWms.warrantyWarnRefer }}
              </el-descriptions-item>
              <el-descriptions-item>
                <template slot="label">保质期</template>
                {{
                  categoryWms.warrantyPeriod
                    ? categoryWms.warrantyPeriod + '/'
                    : null
                }}{{ categoryWms.warrantyPeriodUnit }}
              </el-descriptions-item>
            </el-descriptions>

            <div class="basic-details-title border-none">
              <span class="border-span">生产信息</span>
            </div>
            <el-descriptions title="" :column="4" size="medium" border>
              <el-descriptions-item>
                <template slot="label"> 是否齐套件</template>
                {{ dictType[categoryMes.isCompleteSet] }}
              </el-descriptions-item>
              <el-descriptions-item>
                <template slot="label">消耗波动</template>
                {{
                  categoryMes.consumWave ? categoryMes.consumWave + '%' : null
                }}
              </el-descriptions-item>
              <el-descriptions-item>
                <template slot="label">变动损耗率</template>
                {{
                  categoryMes.changeLossRate
                    ? categoryMes.changeLossRate + '%'
                    : null
                }}
              </el-descriptions-item>
              <el-descriptions-item>
                <template slot="label">固定损耗数</template>
                {{ categoryMes.fixLossNum }}
              </el-descriptions-item>
              <el-descriptions-item>
                <template slot="label">排程类型</template>
                {{ categoryMes.apsType }}
              </el-descriptions-item>
              <el-descriptions-item>
                <template slot="label">允许改型</template>
                {{ dictType[categoryMes.isModify] }}
              </el-descriptions-item>
              <el-descriptions-item>
                <template slot="label">允许返工返修</template>
                {{ dictType[categoryMes.isRework] }}
              </el-descriptions-item>
              <el-descriptions-item>
                <template slot="label">是否返回料</template>
                {{ dictType[categoryMes.isRematerial] }}
              </el-descriptions-item>
              <el-descriptions-item>
                <template slot="label">是否副产品</template>
                {{ dictType[categoryMes.isByProduct] }}
              </el-descriptions-item>
              <el-descriptions-item>
                <template slot="label">是否废品</template>
                {{ dictType[categoryMes.isWaste] }}
              </el-descriptions-item>
              <el-descriptions-item>
                <template slot="label">是否不良品</template>
                {{ dictType[categoryMes.isDefective] }}
              </el-descriptions-item>
            </el-descriptions>

            <div class="basic-details-title border-none">
              <span class="border-span">计划</span>
            </div>
            <el-descriptions title="" :column="4" size="medium" border>
              <el-descriptions-item>
                <template slot="label">固定提前期</template>
                {{ categoryAps.fixLeadTime }}
              </el-descriptions-item>
              <el-descriptions-item>
                <template slot="label">变动提前期</template>
                {{ categoryAps.changeLeadTime }}
              </el-descriptions-item>
              <el-descriptions-item>
                <template slot="label">检验提前期</template>
                {{ categoryAps.checkLeadTime }}
              </el-descriptions-item>
              <el-descriptions-item>
                <template slot="label">累计提前期</template>
                {{ categoryAps.cumLeadTime }}
              </el-descriptions-item>
              <el-descriptions-item>
                <template slot="label">提前期单位</template>
                {{ categoryAps.unit }}
              </el-descriptions-item>
              <el-descriptions-item>
                <template slot="label">订货间隔期</template>
                {{
                  categoryAps.orderIntervalTime
                    ? categoryAps.orderIntervalTime + '/'
                    : null
                }}{{ categoryAps.orderIntervalUnit }}
              </el-descriptions-item>
            </el-descriptions>

            <div class="basic-details-title border-none">
              <span class="border-span">质量配置</span>
            </div>
            <el-descriptions title="" :column="4" size="medium" border>
              <el-descriptions-item>
                <template slot="label">是否来料检验</template>
                {{ dictType[categoryQms.isComeCheck] }}
              </el-descriptions-item>
              <el-descriptions-item>
                <template slot="label">检验方案</template>
                {{ categoryQms.checkFormula }}
              </el-descriptions-item>
              <el-descriptions-item>
                <template slot="label">采购组织</template>
                {{ cgInfo.groupName }}
              </el-descriptions-item>
              <el-descriptions-item>
                <template slot="label">采购员</template>
                {{ cgInfo.name }}
              </el-descriptions-item>
            </el-descriptions>

            <div class="basic-details-title border-none">
              <span class="border-span">备注信息</span>
            </div>
            <el-descriptions title="" :column="4" size="medium" border>
              <el-descriptions-item>
                <template slot="label">附件信息</template>
                {{ categoryObj.fileName }}
              </el-descriptions-item>
              <el-descriptions-item>
                <template slot="label">备注</template>
                {{ categoryObj.remark }}
              </el-descriptions-item>
            </el-descriptions>

            <div class="basic-details-title border-none">
              <span class="border-span">关联信息</span>
            </div>
            <linkMsg
              ref="linkMsgRef"
              :id="categoryObj.id"
              :categoryLevelId="categoryObj.categoryLevelId"
              :categoryLevelGroupId="categoryObj.categoryLevelGroupId"
            />

            <div class="basic-details-title border-none">
              <span class="border-span">文档信息</span>
            </div>
            <!-- <div class="basic-details-title border-none">
              <span class="border-span">文档信息</span>
            </div> -->
            <div class="upload-container">
              <WithView v-model="imageUrl" :limit="1" :assetName="`模具`" />
              <div class="file-list">
                <div>
                  <el-form-item prop="image" label="使用说明书">
                    <fileUpload
                      v-model="attUrl.operatingManual.value"
                      module="main"
                      :showLib="true"
                    />
                  </el-form-item>
                </div>
                <div>
                  <el-form-item prop="image" label="生产许可证书">
                    <fileUpload
                      v-model="attUrl.productionLicence.value"
                      module="main"
                      :showLib="true"
                    />
                  </el-form-item>
                </div>
                <div>
                  <el-form-item prop="image" label="防爆合格证书">
                    <fileUpload
                      v-model="attUrl.explosionProofCertificate.value"
                      module="main"
                      :showLib="true"
                    />
                  </el-form-item>
                </div>
                <div>
                  <el-form-item prop="image" label="检验报告">
                    <fileUpload
                      v-model="attUrl.surveyReport.value"
                      module="main"
                      :showLib="true"
                    />
                  </el-form-item>
                </div>
                <div>
                  <el-form-item prop="image" label="检验周期说明">
                    <fileUpload
                      v-model="attUrl.inspectionCycleManual.value"
                      module="main"
                      :showLib="true"
                    />
                  </el-form-item>
                </div>
                <div>
                  <el-form-item prop="image" label="图纸资料">
                    <fileUpload
                      v-model="attUrl.informationDrawing.value"
                      module="main"
                      :showLib="true"
                    />
                  </el-form-item>
                </div>
                <div>
                  <el-form-item prop="image" label="产品合格证">
                    <fileUpload
                      v-model="attUrl.productCertificate.value"
                      module="main"
                      :showLib="true"
                    />
                  </el-form-item>
                </div>
              </div>
            </div>
          </el-form>
          <div class="basic-details-title border-none">
            <span class="border-span">扩展信息</span>
          </div>
          <el-row>
            <el-form
              :model="itemForm"
              :rules="customRule"
              ref="formCustom"
              class="row-form"
            >
              <el-col
                :span="8"
                v-for="(item, index) in itemForm.addList"
                :key="index"
              >
                <el-form-item
                  :prop="'addList.' + index + '.key'"
                  :rules="{
                    required: true,
                    message: '自定义参数名称不能为空',
                    trigger: 'blur'
                  }"
                >
                  <div class="add-col">
                    <el-input
                      class="col-input"
                      v-model="item.key"
                      placeholder="参数名称"
                    ></el-input>
                    <el-input
                      class="col-input"
                      v-model="item.value"
                      placeholder="参数值"
                    ></el-input>
                    <el-button type="text" @click="delt(item, index)">
                      删除
                    </el-button>
                  </div>
                </el-form-item>
              </el-col>
              <el-col :span="8" v-if="itemForm.addList.length < 10">
                <el-form-item label-width="20px">
                  <el-button type="primary" @click="addItem"
                    >增加自定义参数</el-button
                  >
                </el-form-item>
              </el-col>
            </el-form>
          </el-row>
        </div>
      </div>
    </el-card>
  </div>
</template>

<script>
  import { getAssetInfo, saveOrEdit } from '@/api/ledgerAssets';
  import { listOrganizations } from '@/api/system/organization';
  import fileUpload from '@/components/upload/fileUpload';
  import WithView from '@/components/upload/WithView';
  import imgUpload from '@/components/upload/imgUpload';

  import { sysDict } from '@/utils/sys';
  import linkMsg from '../equipment/components/link-msg.vue';
  import basicInfoVue from '../components/basicInfo.vue';
  import { getDetailInfo } from '@/api/material/list';
  import { getUserPage } from '@/api/system/organization';
  export default {
    components: {
      WithView,
      fileUpload,
      imgUpload,
      linkMsg,
      basicInfoVue
    },
    data() {
      return {
        categoryMold: {},
        cgInfo: {},
        categoryQms: {},
        categoryAps: {},
        categoryMes: {},
        categoryWms: {},
        dictType: {
          1: '是',
          0: '否'
        },
        dictPd: {
          1: '逐个盘点',
          2: '批量盘点'
        },
        categoryObj: {},
        formData: {},
        info: {
          baseInfo: {},
          extraInfo: {}
        },
        customRule: {},
        itemForm: {
          addList: []
        },
        // 图片
        imageUrl: null,
        // 文档信息
        attUrl: {
          operatingManual: {
            value: [],
            sort: 1
          },
          productionLicence: {
            value: [],
            sort: 2
          },
          explosionProofCertificate: {
            value: [],
            sort: 3
          },
          surveyReport: {
            value: [],
            sort: 4
          },
          inspectionCycleManual: {
            value: [],
            sort: 5
          },
          informationDrawing: {
            value: [],
            sort: 6
          },
          productCertificate: {
            value: [],
            sort: 7
          }
        },
        treeData: [],
        btnLoading: false
      };
    },
    created() {
      let id = this.$route.query.id;
      this.getDetilInfo(id);
      this.query();
    },
    methods: {
      // 树形结构数据
      query() {
        listOrganizations()
          .then((list) => {
            this.treeData = this.$util.toTreeData({
              data: list,
              idField: 'id',
              parentIdField: 'parentId'
            });
          })
          .catch((e) => {});
      },

      setImgs(type, sort, info) {
        if (info[0]) {
          this.attUrl[type] = info[0];
          this.attUrl[type].sort = sort;
        } else {
          this.attUrl[type] = null;
        }
      },
      // 处理文档信息
      setWd() {
        let attUrl = [];
        Object.entries(this.attUrl).forEach(([key, value], index) => {
          if (value) {
            attUrl.push(value);
          } else {
            attUrl.push({ sort: index + 1 });
          }
        });
        return attUrl;
      },
      async getDetilInfo(id) {
        const data = await getAssetInfo(id);
        if (data) {
          this.info = data;
          this.$set(this.info, 'baseInfo', data.category.category); //基础信息
          this.$set(this.info, 'extraInfo', data.category.categoryMold); //模具配置
          this.itemForm.addList = this.info.extInfoSelf
            ? this.info.extInfoSelf
            : [];
          if (data.attUrl && data.attUrl.length > 0) {
            // 文档信息
            Object.keys(this.attUrl).forEach((n, index) => {
              this.attUrl[n].value =
                (data.attUrl[index]?.storePath && [data.attUrl[index]]) || [];
            });
          }

          // 设备图片
          this.imageUrl = data.imageUrl || {};
          this.searchMoudol(data.category.category.id);
        }
      },
      async searchMoudol(id) {
        const res = await getDetailInfo(id);
        console.log(res);
        this.categoryObj = {
          ...res.category,
          // deptId:
          fileName: res.category.remarkAttach
            ? res.category.remarkAttach.map((item) => item.name).join(', ')
            : ''
        };
        this.$nextTick(() => {
          this.$refs.basicInfoVueRef.getDetailInfoAugr(this.categoryObj);
        });
        await this.searchDeptNodeClick(res.category.deptLeaderId);
        for (const key in this.depList) {
          if (this.depList[key].id == res.category.deptId) {
            this.depInfo = this.depList[key];
            break;
          }
        }
        for (const key in this.depList) {
          if (this.depList[key].id == res.categoryQms.checkPerson) {
            console.log('++', this.depList[key]);
            this.cgInfo = this.depList[key];
            break;
          }
        }

        this.categoryWms = {
          ...res.categoryWms,
          warrantyPeriodUnit: await sysDict(
            '保质期单位',
            res.categoryWms.warrantyPeriodUnit
          ),
          warrantyWarnRefer: await sysDict(
            '质保预警参考',
            res.categoryWms.warrantyWarnRefer
          )
        };
        this.categoryMes = {
          ...res.categoryMes,
          apsType: await sysDict('排程类型', res.categoryMes.apsType)
        };
        this.categoryAps = {
          ...res.categoryAps,
          orderIntervalUnit: await sysDict(
            '提前期单位',
            res.categoryAps.orderIntervalUnit
          ),
          unit: await sysDict('提前期单位', res.categoryAps.unit)
        };
        this.categoryQms = {
          ...res.categoryQms,
          checkFormula: await sysDict('检验方案', res.categoryQms.checkFormula)
        };
        this.categoryMold = { ...res.categoryMold };
      },
      // 选择所属部门
      async searchDeptNodeClick(id, ids) {
        // 根据部门获取人员
        const res = await getUserPage({
          pageNum: 1,
          size: -1,
          executeGroupId: id
        });
        this.depList = res.list;
      },

      // 选择图片回调
      cbUploadImg(data) {
        if (data.length > 0) {
          this.imageUrl = data[0];
        } else {
          this.imageUrl = '';
        }
      },

      // 删除自定义参数
      delt(item, index) {
        this.itemForm.addList.splice(index, 1);
      },
      // 添加自定义参数
      addItem() {
        if (this.itemForm.addList.length < 10) {
          let item = { key: '', value: '' };
          this.itemForm.addList.push(item);
        } else {
          this.$message.warning('自定义参数最多添加10条');
        }
      },

      // 点击确定保存
      toSave() {
        let extendField = this.itemForm.addList;
        let params = {
          id: this.info.id,
          code: this.info.code,
          fixCode: this.info.fixCode,
          extInfoSelf: extendField,
          ownershipGroupId: this.info.ownershipGroupId,
          rootCategoryLevelId: this.info.rootCategoryLevelId,
          categoryId: this.info.categoryId,
          // positionIds: JSON.parse(this.info.category.categoryLevelPathId).join(','),
          position:
            typeof this.info.positionList == 'string'
              ? {}
              : this.info.positionList[0],
          // 文档信息
          attUrl: this.setWd() || [],
          // // 设备图片
          imageUrl: this.imageUrl || {}
        };
        //============================
        params.extInfo = {
          ownershipGroupId: this.info.ownershipGroupId,
          mouldCode: this.info.mouldCode,
          fixCode: this.info.fixCode,
          codeNumber: this.info.codeNumber,
          startCyTimes: this.info.startCyTimes
        };
        let obj = {};
        params.extInfoSelf.forEach((item) => {
          obj[item.key] = item.value;
        });
        params.extInfoSelf = obj;
        params = { ...params, ...params.extInfo };
        //============================
        this.btnLoading = true;
        this.$refs['formCustom'].validate((valid) => {
          if (valid) {
            saveOrEdit(params)
              .then((res) => {
                if (res) {
                  this.$message.success('模具编辑成功');
                  this.$router.go(-1);
                }
              })
              .finally(() => {
                this.btnLoading = false;
              });
          } else {
            return false;
          }
        });
      },
      // 处理文档信息
      setWd() {
        return Object.values(this.attUrl).map((item) => ({
          ...(item.value[0] || {}),
          sort: item.sort
        }));
      }
    }
  };
</script>

<style lang="scss" scoped>
  .equipment-container {
    background-color: #fff;
    padding: 20px;
    .content {
      padding: 0 20px;
    }
    .page-title {
      width: 100%;
      padding-bottom: 10px;
      border-bottom: 1px solid #ccc;
    }
    .basic-details-title {
      width: 100%;
      display: flex;
      align-items: center;
      justify-content: space-between;
      margin: 15px 0px;
      font-size: 16px;
    }
    .label-none {
      .el-form-item__content {
        margin-left: 0 !important;
      }
    }
    .upload-container {
      display: flex;
      .file-list {
        margin-left: 50px;
        flex: 1;
      }
    }

    .row-form {
      width: 100%;
      .add-col {
        display: flex;
        align-items: center;
        margin-left: 20px;
        .col-input {
          margin-right: 5px;
        }
      }
    }
    .qsbm .el-select {
      width: 100%;
    }
  }
  ::v-deep .el-descriptions {
    .el-form-item {
      margin-bottom: 0px;
    }
  }
</style>
