<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" />
          <businessInformation ref="businessInformationRef" :form="form" />
          <assetInformation ref="assetInformationRef" :form="form" />
          <turnoverCarInformation ref="turnoverCarInformationRef" />
          <warehouseConfigVue ref="warehouseConfigRef" class="ims" />
          <productInfoVue ref="productInfoRef" />
          <planVue ref="planRef" />
          <qualityConfig ref="qualityConfigRef" />
          <footerVue ref="footerVueRef" />
          <documentInformation ref="documentInformationRef" type="周转车" />
          <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 turnoverCarInformation from './components/turnoverCarInformation.vue';
  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 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';
  export default {
    components: {
      warehouseConfigVue,
      productInfoVue,
      planVue,
      qualityConfig,
      footerVue,
      documentInformation,
      DialogGoods,
      assetInformation,
      businessInformation,
      basicInfoVue,
      turnoverCarInformation
    },
    data() {
      return {
        labelStyle: {
          width: '200px'
        },
        contentStyle: {
          width: '400px'
        },
        isLink: true,
        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: {},
        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: '',
        id: ''
      };
    },
    props: {
      showTitle: {
        type: Boolean,
        default: true
      }
    },
    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('7');
      },
      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 = data;
        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.category.categoryVehicle };
            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;
        this.cbexpirationTime = data.expirationTime;
        this.sourceDICT = data.sourceDICT;
        this.networkStatus = data.networkStatus;
        this.positionInfo.deviceDetailAddress = data.deviceDetailAddress;
        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.turnoverCarInformationRef.getDetailInfoAugr(
          this.form.category.categoryVehicle
        );
        // 其他和关联信息
        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]?.storePath && [
                this.form.attUrl[index]
              ]) ||
              [];
          });
          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>
