<template>
  <div id="equipment_edit" class="ele-body baseinfo-container">
    <el-card shadow="never">
      <div class="page-title" v-if="showTitle">
        <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" />
          <equipmentTag :form="form" ref="equipmentTagRef" />
          <businessInformation ref="businessInformationRef" :form="form" />
          <assetInformation ref="assetInformationRef" :form="form" />
          <!-- <warehouseConfigVue ref="warehouseConfigRef" class="ims" /> -->
          <!-- <productInfoVue ref="productInfoRef" /> -->
          <!-- <planVue ref="planRef" /> -->
          <!-- <qualityConfig ref="qualityConfigRef" /> -->
          <!-- <footerVue ref="footerVueRef" /> -->
          <documentInformation ref="documentInformationRef" type="设备" />

          <headerTitle title="物联参数" style="margin-top: 15px"></headerTitle>

          <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 warehouseConfigVue from '../components/warehouseConfig.vue';
import productInfoVue from '../components/productInfo.vue';
import planVue from '../components/plan.vue';
import qualityConfig from '../components/qualityConfig.vue';
import footerVue from '../components/footer.vue';
import documentInformation from '../components/documentInformation.vue';
import equipmentTag from '../components/equipmentTag.vue';
import basicInfoVue from '../components/basicInfo.vue';
import DialogGoods from '../components/DialogGoods';
import assetInformation from '../components/assetInformation.vue';
import businessInformation from '../components/businessInformation.vue';
import { getDetails } from '@/api/classifyManage/itemInformation';
import {
  saveOrEdit,
  getAssetInfo,
  getCode,
  getAssetNum
} from '@/api/ledgerAssets';
const equipmentLabelJson = [
  {
    LJSB: '2', //老旧设备
    SHSB: '2', //涉火设备
    SHLJSB: '2', //涉火老旧设备
    GZSB: '2', //关重设备
    GJSB: '2', //关键设备
    TZSB: '2', //特种设备
    HBSB: '2', //环保设备
    ZYSCSB: '2', //主要生产设备
    FZSCSB: '2', //辅助生产设备
    KYSB: '2' //科研设备
  }
];
export default {
  components: {
    warehouseConfigVue,
    productInfoVue,
    planVue,
    qualityConfig,
    footerVue,
    documentInformation,
    DialogGoods,
    assetInformation,
    businessInformation,
    basicInfoVue,
    equipmentTag
  },
  props: {
    showTitle: {
      type: Boolean,
      default: true
    }
  },
  data() {
    return {
      labelStyle: {
        width: '200px'
      },
      contentStyle: {
        width: '400px'
      },
      isLink: true,
      title: '新建设备信息',
      pageType: 'add',
      btnLoading: false,
      // 设备主键id
      id: '',
      form: {
        extInfoSelf: [],
        // 基本信息
        code: '',
        name: '',
        productTime: '',
        workstation:'',
        equipmentLabelJson
      },
      rules: {
        name: [{ required: true, message: '请输入设备名称', trigger: 'blur' }],
        code: [{ required: true, message: '请输入设备编码', trigger: 'blur' }]
      },
      // 基本信息
      basicInfo: {},
      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: '1',
      // 物联ID
      iotId: '',
      // 回显过保时间
      cbexpirationTime: '',
      // 生命周期
      sourceDICT: '',
      // 网络状态
      networkStatus: '',
      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: {
    handlwpbm() {
      this.$refs.DialogGoods.open('0', true);
    },
    async cbDialogGoods(data) {
      let res = await getDetails(data.id);
      if (!data.extInfoSelf) {
        data.extInfoSelf = [];
      }
      // if (!data.workstation) {
      //   data.workstation = {};
      // }
      if (!data.isPublic) {
        data.isPublic = 0;
      }
      this.form = Object.assign({}, this.form, data);
      console.log(this.form);

      this.form.category = res;
      this.basicInfo = data;
      this.form.rootCategoryLevelId = this.basicInfo.categoryLevelPathId
        .split(',')[0]
        .replace('[', '');
      this.form.categoryId = this.basicInfo.id;
      this.form.name = this.basicInfo.name;
      this.form.code = data.code; //Date.now(); //res.data[0].onlyCode;
      this.initOtherMsg();
    },
    // 计算过保时间
    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) => {
        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.extInfo = { ...this.form };
          let obj = {};
          par.extInfoSelf.forEach((item) => {
            obj[item.key] = item.value;
          });
          // console.log('sasasasa', par);
          // return;
          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;
          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() {
      console.log(this.attUrl)
      return Object.values(this.attUrl).map((item) => ({
        value:item.value||[],
        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 = Object.assign({}, this.form, data);
      console.log(this.form, 'dsadasd');
      this.form.lifeCycle = this.form.lifeCycle + '';
      this.form.location = data.deviceLocationName.split(',');
      this.basicInfo = data;
      this.cbexpirationTime = data.expirationTime;
      this.sourceDICT = data.sourceDICT;
      this.networkStatus = data.networkStatus;
      this.positionInfo.deviceDetailAddress = data.deviceDetailAddress;
      if (this.form.equipmentLabelJson.length == 0) {
        this.form.equipmentLabelJson = equipmentLabelJson;
      }
      this.initOtherMsg();
      // 设备图片
      this.imageUrl = data.imageUrl;
      // 物联参数
      this.isIotEnable = data.isIotEnable;
      this.iotId = data.iotId;
    },
    async initOtherMsg() {
      // 基本信息
      this.$refs.basicInfoVueRef.getDetailInfoAugr(this.form.category.category);
      // 仓储配置
      // this.$refs.warehouseConfigRef.getDetailInfoAugr(
      //   this.form.category.categoryWms
      // );
      // 生产信息
      // this.$refs.productInfoRef.getDetailInfoAugr(
      //   this.form.category.categoryMes
      // );
      // 计划配置
      // this.$refs.planRef.getDetailInfoAugr(this.form.category.categoryAps);
      // 质量配置
      // this.$refs.qualityConfigRef.getDetailInfoAugr(
      //   this.form.category.categoryQms
      // );
      // 其他和关联信息
      // this.$refs.footerVueRef.getDetailInfoAugr(this.form.category.category);
      // 文档信息
      if (this.form.attUrl && this.form.attUrl.length > 0) {
        Object.keys(this.attUrl).forEach((n, index) => {
          this.attUrl[n].value =this.form.attUrl[index].value||[]
        });
        this.$refs.documentInformationRef.getDetailInfoAugr(this.attUrl);
      }
    },
    // 设置标准产能
    setbzcn(val) {
      if (!val) {
        return '';
      }
      let item = JSON.parse(val);
      return item.standardCapacity || '';
    }
  }
};
</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>
