<template>
  <div id="equipment_edit" class="ele-body baseinfo-container">
    <el-card shadow="never">
      <div class="page-title">
        <el-page-header @back="$router.go(-1)">
          <div slot="content" class="pageContent">
            <div>{{ title }}</div>
          </div>
        </el-page-header>
        <div>
          <el-button type="primary" @click="submit" :loading="btnLoading"
            >确定</el-button
          >
        </div>
      </div>
      <div v-if="pageType == 'add'">
        <el-button type="primary" plain @click="handlwpbm">选择物品</el-button>
      </div>
      <el-form
        label-width="120px"
        :model="{ ...form, ...positionInfo }"
        ref="form"
        :rules="rules"
      >
        <div class="content">
          <basicInfoVue ref="basicInfoVueRef" />
          <businessInformation ref="businessInformationRef" :form="form" />
          <assetInformation
            ref="assetInformationRef"
            :isLock="true"
            :form="form"
          />
          <div class="basic-details-title border-none">
            <span class="border-span">仓储配置</span>
          </div>
          <el-descriptions
            :label-style="labelStyle"
            :contentStyle="contentStyle"
            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>
              {{ 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"
            :label-style="labelStyle"
            :contentStyle="contentStyle"
            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-item>
              <template slot="label"> 标准产能 </template>
              {{ setbzcn(basicInfo.extendField) }}
            </el-descriptions-item>
          </el-descriptions>

          <div class="basic-details-title border-none">
            <span class="border-span">其他信息</span>
          </div>
          <el-descriptions
            :label-style="labelStyle"
            :contentStyle="contentStyle"
            title=""
            :column="2"
            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
            v-if="isLink"
            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="upload-container">
            <WithView v-model="imageUrl" :limit="1" />
            <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>
          <div class="basic-details-title border-none">
            <span class="border-span">物联参数</span>
          </div>
          <el-row>
            <el-col>
              <el-form-item label="是否启用物联">
                <el-switch
                  v-model="isIotEnable"
                  active-text="开"
                  inactive-text="关"
                  :active-value="1"
                  :inactive-value="0"
                >
                </el-switch>
              </el-form-item>
            </el-col>
            <el-col>
              <el-form-item label="物联ID">{{ iotId }}</el-form-item>
            </el-col>
          </el-row>
          <div class="basic-details-title border-none">
            <span class="border-span">扩展信息</span>
          </div>
          <div class="kzzd">
            <el-row>
              <el-col
                :span="24"
                v-for="(item, index) in form.extInfoSelf"
                :key="index"
                style="margin-bottom: 20px"
              >
                <el-form-item
                  label-width="0"
                  :prop="'extInfoSelf.' + 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
                      class="del"
                      type="text"
                      @click="delt(item, index)"
                    >
                      删除
                    </el-button>
                  </div>
                </el-form-item>
              </el-col>
              <el-col :span="24" v-if="form.extInfoSelf.length < 10">
                <el-form-item label-width="0">
                  <el-button
                    class="primarybutton"
                    type="primary"
                    @click="addItem"
                    >增加自定义参数</el-button
                  >
                </el-form-item>
              </el-col>
            </el-row>
          </div>
        </div>
      </el-form>
      <DialogGoods
        ref="DialogGoods"
        @succeed="cbDialogGoods"
        width="1200px"
      ></DialogGoods>
    </el-card>
  </div>
</template>

<script>
  import basicInfoVue from '../components/basicInfo.vue';
  import { getDetailInfo } from '@/api/material/list';
  import selectTree from '@/components/selectTree';
  import DeptSelect from '@/components/CommomSelect/dept-select.vue';
  import FactoryLineSelect from '@/components/CommomSelect/factory-line-select.vue';
  import WorkshopSelect from '@/components/CommomSelect/workshop-select.vue';
  import FactoryAreaSelect from '@/components/CommomSelect/factory-area-select.vue';
  import WorkingProcedureSelect from '@/components/CommomSelect/working-procedure-select.vue';
  import factorySelect from '@/components/CommomSelect/factory-select.vue';
  import fileUpload from '@/components/upload/fileUpload';
  import WithView from '@/components/upload/WithView';
  import imgUpload from '@/components/upload/imgUpload';
  import { cityDataLabel } from 'ele-admin/packages/utils/regions';
  import personSelect from '@/components/CommomSelect/person-select.vue';
  import { getDetails } from '@/api/classifyManage/itemInformation';
  import { sysDict, isExit } from '@/utils/sys';
  import linkMsg from './components/link-msg.vue';
  import DialogGoods from './components/DialogGoods';
  import assetInformation from '../components/assetInformation.vue';
  import businessInformation from '../components/businessInformation.vue';
  import {
    saveOrEdit,
    getAssetInfo,
    factoryworkstation,
    getCode,
    getAssetNum
  } from '@/api/ledgerAssets';
  import { getUserPage } from '@/api/system/organization';
  import warehouseDefinition from '@/api/warehouseManagement/warehouseDefinition';
  import { listWorkshopByParentId, listFactoryLine } from '@/api/factoryModel';
  import { getByCode } from '@/api/system/dictionary-data';
  export default {
    components: {
      linkMsg,
      selectTree,
      FactoryLineSelect,
      WithView,
      WorkshopSelect,
      FactoryAreaSelect,
      WorkingProcedureSelect,
      fileUpload,
      imgUpload,
      factorySelect,
      DialogGoods,
      DeptSelect,
      personSelect,
      assetInformation,
      businessInformation,
      basicInfoVue
    },
    data() {
      return {
        treeList: [], // 使用岗位树
        userList: [], // 人员列表
        labelStyle: {
          width: '200px'
        },
        contentStyle: {
          width: '400px'
        },
        isLink: true,
        categoryObj: {},
        dictType: {
          1: '是',
          0: '否'
        },
        dictPd: {
          1: '逐个盘点',
          2: '批量盘点'
        },
        categoryMes: {
          isModify: '',
          isRework: '',
          isRematerial: '',
          isByProduct: '',
          isWaste: '',
          isDefective: ''
        },
        categoryWms: {}, //仓储
        title: '新建设备信息',
        pageType: 'add',
        btnLoading: false,
        // 设备主键id
        id: '',
        form: {
          extInfoSelf: [],
          // 基本信息
          code: '',
          name: '',
          productTime: '',
          workstation: {}
        },
        rules: {
          name: [
            { required: true, message: '请输入设备名称', trigger: 'blur' }
          ],
          // location: [{ validator: addressValidation, trigger: 'change' }],
          code: [{ required: true, message: '请输入设备编码', trigger: 'blur' }]
        },
        // 基本信息
        basicInfo: {},
        assetInfo: {},
        // 资产信息
        zcInfo: {
          // 详细地址
          deviceDetailAddress: '',
          workstation: '',
          // 	固定资产编码
          fixCode: '',
          // 颜色
          color: '',
          // 重量
          weight: '',
          // 维护部门code
          repairGroupId: '',
          repairDeptName: '',
          repairUserId: '',
          // 权属部门
          ownershipGroupId: '',
          ownershipUserId: '',
          // 设备用途
          purpose: '',
          // 工序
          roteId: '',
          roteName: '',
          //品牌
          brand: '',
          // 	供应商code
          supplierId: '',
          // 厂房
          factoryRoomId: '',
          roteCode: '',
          codeNumber: '',
          // 使用人
          usePersonId: '',
          // 有效期开始
          startTime: '',
          // 有效结束
          endTime: '',
          // 级别
          level: '',
          // 状态
          status: '',
          // 负责人
          chargePersonId: '',
          // 入账日期
          entryDate: '',
          // 周期
          cycle: '',
          // 备注
          remark: '',
          // 使用岗位
          postId: ''
        },
        positionInfo: {
          // 详细地址
          deviceDetailAddress: '',
          // 请选择产线
          lineCode: '',
          lineName: '',
          // 请选择车间
          workshopCode: '',
          workshopName: '',
          // 请选择工厂
          factoryCode: '',
          factoryName: ''
        },
        // 图片
        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
          }
        },
        // 是否开始物联
        isIotEnable: true,
        // 物联ID
        iotId: '',
        // 回显过保时间
        cbexpirationTime: '',
        // 生命周期
        sourceDICT: '',
        // 网络状态
        networkStatus: '',
        options: {
          deptList: [],
          repairUserId: [],
          ownershipUserId: [],
          supplierId: [],
          brand: [],
          cityDataLabel,
          assetLevel: [], // 资产级别
          deliveryCycle: [] // 送检周期
        },
        depList: [],
        warehouseList: [],
        areaList: [],
        shelvesList: [],
        suppList: [],
        zjList: [],
        cxList: [],
        id: ''
      };
    },
    watch: {},
    computed: {
      // 过保时间
      expirationTime() {
        if (this.form.productTime && this.basicInfo.expirationDate) {
          return this.setGbTime(
            this.form.productTime,
            this.basicInfo.expirationDate,
            this.basicInfo.expirationDateUnit
          );
        } else {
          return '';
        }
      }
    },
    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: {
      isExit,
      handlwpbm() {
        this.$refs.DialogGoods.open('15');
      },
      async cbDialogGoods(data) {
        let res = await getDetails(data.id);
        console.log(res);
        this.form.category = res;
        this.initOtherMsg(this.form);
        if (!data.extInfoSelf) {
          data.extInfoSelf = [];
        }
        if (!data.workstation) {
          data.workstation = {};
        }
        this.form = data;
        this.basicInfo = data;
        this.assetInfo = data;
        console.log('this.basicInfo---------');
        console.log(this.basicInfo);
        if (typeof this.basicInfo.categoryLevelPathId === 'string') {
          let categoryLevelPathId = JSON.parse(
            this.basicInfo.categoryLevelPathId
          );
          if (Array.isArray(categoryLevelPathId)) {
            this.form.rootCategoryLevelId = JSON.parse(
              this.basicInfo.categoryLevelPathId
            )[0];
          } else {
            this.form.rootCategoryLevelId = categoryLevelPathId;
          }
        } else {
          if (Array.isArray(this.form.rootCategoryLevelId)) {
            this.form.rootCategoryLevelId =
              this.basicInfo.categoryLevelPathId[0];
          } else {
            this.form.rootCategoryLevelId = this.basicInfo.categoryLevelPathId;
          }
        }
        this.form.categoryId = this.basicInfo.id;
        this.form.name = this.basicInfo.name;
        // let res = await getAssetNum({
        //   assetCode: this.basicInfo.code,
        //   num: 1
        // });
        this.form.code = data.code; //Date.now(); //res.data[0].onlyCode;
        this.$refs.basicInfoVueRef.getDetailInfoAugr(this.form);
      },
      // 计算过保时间
      setGbTime(basic, value, type) {
        basic = Date.parse(basic);
        let time;
        switch (type) {
          case 'minute':
            time = value * 1000 * 60;
            break;
          case 'hour':
            time = value * 1000 * 60 * 60;
            break;
          case 'day':
            time = value * 1000 * 60 * 60 * 24;
            break;
          case 'month':
            time = value * 1000 * 60 * 60 * 24 * 30;
            break;
          case 'year':
            time = value * 1000 * 60 * 60 * 24 * 365;
            break;
          default:
            break;
        }

        let num = basic + time;
        return parseTime(num);
      },
      // 添加自定义参数
      addItem() {
        if (this.form.extInfoSelf.length < 10) {
          let item = { key: '', value: '' };
          this.form.extInfoSelf.push(item);
        } else {
          this.$message.warning('自定义参数最多添加10条');
        }
      },
      // 删除自定义参数
      delt(item, index) {
        this.form.extInfoSelf.splice(index, 1);
      },
      // 提交
      submit() {
        if (JSON.stringify(this.basicInfo) === '{}' && this.pageType == 'add') {
          return this.$message.error('请选择物品编码');
        }
        this.$refs.form.validate(async (valid) => {
          console.log(this.form);
          if (valid) {
            let par = {
              //基本信息
              ...this.form,
              assetType: 1,
              // 资产信息
              positionIds: '1,1,1,1',
              position: {
                detailPosition: this.positionInfo.deviceDetailAddress,
                pathIds: `${
                  this.positionInfo.factoryCode
                    ? this.positionInfo.factoryCode + ','
                    : ''
                }${
                  this.positionInfo.workshopCode
                    ? this.positionInfo.workshopCode + ','
                    : ''
                }${this.positionInfo.lineCode}`,
                pathName: `${
                  this.positionInfo.factoryName
                    ? this.positionInfo.factoryName + ','
                    : ''
                }${
                  this.positionInfo.workshopName
                    ? this.positionInfo.workshopName + ','
                    : ''
                }${this.positionInfo.lineName}`,
                type: '1',
                num: 1
              },
              // 文档信息
              attUrl: this.setWd() || [],
              // // 设备图片
              imageUrl: this.imageUrl || {},
              // 是否启用物联
              isIotEnable: this.isIotEnable
              // // 扩展字段

              // extInfoSelf: this.setKz()
            };

            par.deviceLocationName = par.location
              ? par.location.toString()
              : '';
            // par.sss = par.position.deviceDetailAddress;
            //==
            //============================
            par.extInfo = { ...this.form };
            let obj = {};
            par.extInfoSelf.forEach((item) => {
              obj[item.key] = item.value;
            });
            par.extInfoSelf = obj;
            //============================
            if (this.pageType == 'edit') {
              par.id = this.id;
            } else {
              const batchNo = await getCode('lot_number_code');
              const res = await getAssetNum({
                assetCode: par.code,
                batchNum: batchNo,
                num: 1
              });
              console.log(res);
              par.code = res.data.shift().onlyCode;
              par.id = '';
            }
            this.btnLoading = true;
            console.log('sasasasa', par);
            saveOrEdit(par)
              .then((res) => {
                this.$message.success('操作成功');
                this.$router.go(-1);
              })
              .finally(() => {
                this.btnLoading = false;
              });
          } else {
            console.log('error submit!!');
            return false;
          }
        });
      },
      // 处理扩展字段
      setKz() {
        return this.form.extInfoSelf || [];
      },
      // 处理文档信息
      setWd() {
        return Object.values(this.attUrl).map((item) => ({
          ...(item.value[0] || {}),
          sort: item.sort
        }));
      },
      // 获取设备详情
      async getInfo() {
        const data = await getAssetInfo(this.id);
        data.extInfoSelf = data.extInfoSelf || [];
        if (!data.workstation) {
          data.workstation = {};
        }
        if (!data.isPublic) {
          data.isPublic = 0;
        }
        this.form = data;
        this.form.location = data.deviceLocationName.split(',');
        this.basicInfo = data.category;
        this.assetInfo = data.category.category;
        this.cbexpirationTime = data.expirationTime;
        this.sourceDICT = data.sourceDICT;
        this.networkStatus = data.networkStatus;
        this.positionInfo.deviceDetailAddress = data.deviceDetailAddress;
        this.initOtherMsg(data);
        // 填充基本信息
        this.$nextTick(() => {
          console.log(this.form);
          this.$refs.basicInfoVueRef.getDetailInfoAugr(
            this.form.category.category
          );
        });
        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.isIotEnable = data.isIotEnable;
        this.iotId = data.iotId;
      },
      async initOtherMsg(data) {
        this.isLink = false;
        // 仓储配置信息
        this.categoryWms = {
          ...data.category.categoryWms,
          warrantyWarnRefer: await sysDict(
            '质保预警参考',
            data.category.categoryWms.warrantyWarnRefer
          ),
          warrantyPeriodUnit: await sysDict(
            '保质期单位',
            data.category.categoryWms.warrantyPeriodUnit
          )
        };
        // 生产信息
        this.categoryMes = {
          ...data.category.categoryMes,
          apsType: await sysDict('排程类型', data.category.categoryMes.apsType)
        };
        this.categoryObj = {
          ...data.category.category,
          fileName: data.category.category.remarkAttach
            ? data.category.category.remarkAttach
                .map((item) => item.name)
                .join(', ')
            : ''
        };
        this.isLink = true;
      },
      // 设置标准产能
      setbzcn(val) {
        if (!val) {
          return '';
        }
        let item = JSON.parse(val);
        return item.standardCapacity || '';
      },
      hanldWorkshopCode(val, item) {
        this.positionInfo.workshopName = item?.name;
        // 重置
        this.options.workshopCode = [];
        this.options.lineCode = [];
        // 获取产线
        this.$nextTick(() => {
          // this.$refs.FactoryLineSelectRef.getList();
        });
      },
      hanldlineCodeCode(val, item) {
        this.positionInfo.lineName = item?.name;
      }
    }
  };
</script>

<style lang="scss" scoped>
  ::v-deep .descriptions {
    margin-bottom: 10px;
  }
  .baseinfo-container .basic-details-title {
    font-size: 16px;
    margin: 15px 0;
  }
  .upload-container {
    display: flex;
    justify-content: flex-start;
    .file-list {
      margin-left: 50px;
      flex: 1;
    }
  }
  .equipment-container {
    .label-none {
      .el-form-item__content {
        margin-left: 0 !important;
      }
    }
  }
  .sbwz {
    .item {
      width: 120px !important;
    }
    .item + .item {
      margin-left: 10px;
    }
    .item-input {
      width: 350px !important;
    }
  }
  .input {
    width: 100%;
  }
  .kzzd {
    width: 500px;
    .add-col {
      display: flex;
      .col-input {
        & + .col-input {
          margin-left: 10px;
        }
      }
      .del {
        margin-left: 10px;
      }
    }
  }
  ::v-deep .el-descriptions {
    .el-form-item {
      margin-bottom: 0px;
    }
  }
</style>
