<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>{{ title }}</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 v-if="pageType == 'add'">
          <el-button type="primary" plain @click="handlwpbm"
            >选择物品</el-button
          >
        </div>
        <div class="content">
          <el-form label-width="100px">
            <!-- <div class="basic-details-title border-none">
              <span class="border-span">基本信息</span>
            </div>
            <el-descriptions title="" :column="3" size="medium" border>
              <el-descriptions-item>
                <template slot="label"> 办公设备编码 </template>
                {{ info.code }}
              </el-descriptions-item>
              <el-descriptions-item>
                <template slot="label"> 办公设备名称 </template>
                {{ info.name }}
              </el-descriptions-item>
              <el-descriptions-item>
                <template slot="label"> 牌号 </template>
                {{ info.baseInfo.brandNum }}
              </el-descriptions-item>
              <el-descriptions-item>
                <template slot="label"> 型号 </template>
                {{ info.baseInfo.modelType }}
              </el-descriptions-item>
              <el-descriptions-item>
                <template slot="label"> 规格 </template>
                {{ info.extraInfo.specification }}
              </el-descriptions-item>
              <el-descriptions-item>
                <template slot="label"> 芯杆数量 </template>
                {{ info.extraInfo.coreBarNum }}
              </el-descriptions-item>
              <el-descriptions-item>
                <template slot="label"> 模孔数量 </template>
                {{ info.extraInfo.dieHoleNum }}
              </el-descriptions-item>
              <el-descriptions-item>
                <template slot="label"> 收缩系数 </template>
                {{ info.extraInfo.shrinkEffictive }}
              </el-descriptions-item>
              <el-descriptions-item>
                <template slot="label"> 下冲头数量 </template>
                {{ info.extraInfo.downPunchNum }}
              </el-descriptions-item>
              <el-descriptions-item>
                <template slot="label"> 上冲头数量 </template>
                {{ info.extraInfo.upperPunchNum }}
              </el-descriptions-item>
              <el-descriptions-item>
                <template slot="label"> 最大冲压次数 </template>
                {{ info.extraInfo.maxCyTimes }}
              </el-descriptions-item>
              <el-descriptions-item>
                <template slot="label"> 计量单位 </template>
                {{ info.baseInfo.measuringUnit }}
              </el-descriptions-item>
              <el-descriptions-item :span="2">
                <template slot="label"> 分类 </template>
                {{ info.baseInfo.categoryLevelPath }}
              </el-descriptions-item>
              <el-descriptions-item>
                <template slot="label"> 采购日期 </template>
                {{info.category.procurementTime}}
              </el-descriptions-item>
              <el-descriptions-item>
                <template slot="label"> 过保日期 </template>
                {{info.category.expirationTime}}
              </el-descriptions-item>
            </el-descriptions> -->
            <basicInfoVue ref="basicInfoVueRef" />
            <businessInformation ref="businessInformationRef" :form="info" />
            <assetInformation ref="assetInformationRef" :form="info" />
            <!-- <div class="basic-details-title border-none">
              <span class="border-span">资产信息</span>
            </div>
            <el-row>
              <el-col :md="8" :xs="8" :sm="8">
                <el-form-item label="固资编码">
                  <el-input size="small" v-model="info.fixCode"></el-input>
                </el-form-item>
              </el-col>
              <el-col :md="8" :xs="8" :sm="8">
                <el-form-item label="编号">
                  <el-input size="small" v-model="info.codeNumber"></el-input>
                </el-form-item>
              </el-col>
              <el-col :md="8" :xs="8" :sm="8">
                <el-form-item
                  label="权属部门"
                  prop="ownershipGroupId"
                  class="qsbm"
                >
                  <ele-tree-select
                    clearable
                    :data="treeData"
                    v-model="info.ownershipGroupId"
                    placeholder="请选择"
                    default-expand-all
                    labelKey="name"
                    valueKey="id"
                  />
                </el-form-item>
              </el-col>
            </el-row> -->
            <div class="basic-details-title border-none">
              <span class="border-span">舟皿信息</span>
            </div>
            <el-descriptions
              title=""
              :column="3"
              size="medium"
              :label-style="labelStyle"
              :contentStyle="contentStyle"
              border
            >
              <el-descriptions-item>
                <template slot="label">长</template>
                {{
                  categoryPallet.palletLen
                    ? categoryPallet.palletLen + 'mm'
                    : ''
                }}
              </el-descriptions-item>
              <el-descriptions-item>
                <template slot="label">宽</template>
                {{ categoryPallet.wilde ? categoryPallet.wilde + 'mm' : '' }}
              </el-descriptions-item>
              <el-descriptions-item>
                <template slot="label">高</template>
                {{ categoryPallet.height ? categoryPallet.height + 'mm' : '' }}
              </el-descriptions-item>
              <el-descriptions-item>
                <template slot="label">槽数</template>
                {{ categoryPallet.slotNum ? categoryPallet.slotNum : '' }}
              </el-descriptions-item>
              <el-descriptions-item>
                <template slot="label">角度</template>
                {{
                  categoryPallet.angle > 0
                    ? angleOptions[categoryPallet.angle]
                    : ''
                }}
              </el-descriptions-item>
            </el-descriptions>
            <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>
      <DialogGoods
        ref="DialogGoods"
        @succeed="cbDialogGoods"
        width="1200px"
      ></DialogGoods>
    </el-card>
  </div>
</template>

<script>
  import { getDetails } from '@/api/classifyManage/itemInformation';
  import DialogGoods from '../components/DialogGoods';
  import { getDetailInfo } from '@/api/material/list';
  import {
    getAssetInfo,
    saveOrEdit,
    getCode,
    getAssetNum
  } 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 basicInfoVue from '../components/basicInfo.vue';
  import businessInformation from '../components/businessInformation.vue';
  import assetInformation from '../components/assetInformation.vue';
  export default {
    components: {
      WithView,
      fileUpload,
      imgUpload,
      assetInformation,
      basicInfoVue,
      businessInformation,
      DialogGoods
    },
    data() {
      return {
        formData: {},
        labelStyle: {
          width: '200px'
        },
        contentStyle: {
          width: '400px'
        },
        info: {
          baseInfo: {},
          extraInfo: {}
        },
        customRule: {},
        itemForm: {
          addList: []
        },
        // 图片
        imageUrl: null,
        angleOptions: {
          1: 'A',
          2: '非A'
        },
        // 文档信息
        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,
        id: '',
        basicInfo: '',
        pageType: '',
        categoryPallet: {},
        title: ''
      };
    },
    async created() {
      if (this.$route.query.id) {
        this.pageType = 'edit';
        this.id = this.$route.query.id;
        await this.getInfo();
        this.title = '编辑舟皿信息';
        // this.getgys();
        // await this._getWarehouseChildren();
      } else {
        this.pageType = 'add';
        this.title = '新增舟皿信息';
      }
    },
    methods: {
      handlwpbm() {
        this.$refs.DialogGoods.open('8');
      },
      async cbDialogGoods(data) {
        // this.searchMoudol(data.category.category.id);
        let res = await getDetails(data.id);
        console.log(res);
        this.info.category = res;
        if (!data.extInfoSelf) {
          data.extInfoSelf = [];
        }
        if (!data.workstation) {
          data.workstation = {};
        }
        this.info = data;
        this.categoryPallet = { ...res.categoryPallet };
        this.basicInfo = data;
        console.log(this.basicInfo);
        if (typeof this.basicInfo.categoryLevelPathId === 'string') {
          let categoryLevelPathId = JSON.parse(
            this.basicInfo.categoryLevelPathId
          );
          if (Array.isArray(categoryLevelPathId)) {
            this.info.rootCategoryLevelId = JSON.parse(
              this.basicInfo.categoryLevelPathId
            )[0];
          } else {
            this.info.rootCategoryLevelId = categoryLevelPathId;
          }
        } else {
          if (Array.isArray(this.info.rootCategoryLevelId)) {
            this.info.rootCategoryLevelId =
              this.basicInfo.categoryLevelPathId[0];
          } else {
            this.info.rootCategoryLevelId = this.basicInfo.categoryLevelPathId;
          }
        }
        this.info.categoryId = this.basicInfo.id;
        this.info.name = this.basicInfo.name;
        this.info.code = data.code; //Date.now(); //res.data[0].onlyCode;
        this.$refs.basicInfoVueRef.getDetailInfoAugr(this.info);
      },
      // 树形结构数据
      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 getInfo() {
        const data = await getAssetInfo(this.id);
        console.log(data);
        if (data) {
          if (!data.workstation) {
            data.workstation = {};
          }
          this.info = data;
          this.info = data;
          this.basicInfo = data;
          this.info.location = data.deviceLocationName.split(',');
          this.info.baseInfo = data.category.category;
          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 || {};
          const res = await getDetailInfo(data.category.category.id);
          this.categoryObj = {
            ...res.category,
            // deptId:
            fileName: res.category.remarkAttach
              ? res.category.remarkAttach.map((item) => item.name).join(', ')
              : ''
          };
          // 舟皿信息
          this.categoryPallet = { ...res.categoryPallet };
          this.$nextTick(() => {
            this.$refs.basicInfoVueRef.getDetailInfoAugr(this.categoryObj);
          });
        }
      },

      // 选择图片回调
      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条');
        }
      },

      // 点击确定保存
      async toSave() {
        if (JSON.stringify(this.basicInfo) === '{}' && this.pageType == 'add') {
          return this.$message.error('请选择物品编码');
        }
        let extendField = this.itemForm.addList;
        let params = {
          ...this.info,
          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(','),
          deviceLocationName: this.info.location
            ? this.info.location.join(',')
            : '',
          position: {
            type: '1',
            num: 1
          },
          // 文档信息
          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 };
        if (this.pageType == 'add') {
          const batchNo = await getCode('lot_number_code');
          const res = await getAssetNum({
            assetCode: params.code,
            batchNum: batchNo,
            num: 1
          });
          params.code = res.data.shift().onlyCode;
          params.id = '';
        }
        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%;
    }
  }
</style>
