<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 label-width="120px">
          <div class="content">
            <basicInfoVue ref="basicInfoRef" />
            <businessInformation ref="businessInformationRef" :form="info" />
            <assetInformation ref="assetInformationRef" :form="info" />
            <!-- <div class="basic-details-title border-none">
              <span class="border-span">资产信息</span>
            </div>

            <el-form label-width="90px">
              <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 class="input" 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
                      class="input"
                      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">
                    <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>
            </el-form> -->

            <div class="baseinfo-container">
              <warehouseConfigVue ref="warehouseConfigRef" class="ims" />
              <productInfoVue ref="productInfoRef" />
              <planVue ref="planRef" />
              <qualityConfig ref="qualityConfigRef" />
              <footerVue ref="footerVueRef" />
            </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>
            <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>
      </div>
      <DialogGoods
        ref="DialogGoods"
        @succeed="cbDialogGoods"
        width="1200px"
      ></DialogGoods>
    </el-card>
  </div>
</template>

<script>
  import DialogGoods from '../components/DialogGoods';
  import {
    getAssetInfo,
    saveOrEdit,
    getCode,
    getAssetNum
  } from '@/api/ledgerAssets';
  import { listOrganizations } from '@/api/system/organization';
  import WithView from '@/components/upload/WithView';
  import dictMixins from '@/mixins/dictMixins';
  import { getDetails } from '@/api/classifyManage/itemInformation';
  import { sysDict } from '@/utils/sys';

  import basicInfoVue from '../components/basicInfo.vue';
  import businessInformation from '../components/businessInformation.vue';
  import assetInformation from '../components/assetInformation.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';
  export default {
    mixins: [dictMixins],
    components: {
      WithView,
      basicInfoVue,
      warehouseConfigVue,
      productInfoVue,
      planVue,
      qualityConfig,
      footerVue,
      assetInformation,
      businessInformation,
      DialogGoods
    },
    data() {
      return {
        labelStyle: {
          width: '200px'
        },
        contentStyle: {
          width: '400px'
        },
        formData: {},
        info: {
          category: {},
          warehouseDetail: {}
        },
        customRule: {},
        itemForm: {
          addList: []
        },
        imageUrl: {},
        treeData: [],
        btnLoading: false,
        categoryVehicle: {},
        // 基本信息
        basicInfo: {},
        id: '',
        pageType: '',
        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 = '新增办公设备信息';
      }
      // let id = this.$route.query.id;
      // this.getDetilInfo(id);
      // this.query();
    },
    methods: {
      handlwpbm() {
        this.$refs.DialogGoods.open('16');
      },
      async cbDialogGoods(data) {
        // this.searchMoudol(data.category.category.id);
        let res = await getDetails(data.id);
        console.log(res);
        if (!data.extInfoSelf) {
          data.extInfoSelf = [];
        }
        if (!data.workstation) {
          data.workstation = {};
        }
        this.info = data;
        this.info.category = res;
        this.basicInfo = 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.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.$nextTick(() => {
          this.$refs.basicInfoRef.getDetailInfoAugr(
            this.info.category.category
          );
          this.$refs.warehouseConfigRef.getDetailInfoAugr(
            this.info.category.categoryWms
          );
          this.$refs.productInfoRef.getDetailInfoAugr(
            this.info.category.categoryMes
          );
          this.$refs.planRef.getDetailInfoAugr(this.info.category.categoryAps);
          this.$refs.qualityConfigRef.getDetailInfoAugr(
            this.info.category.categoryQms
          );
          this.$refs.footerVueRef.getDetailInfoAugr(
            this.info.category.category
          );
        });
      },
      // 树形结构数据
      query() {
        listOrganizations()
          .then((list) => {
            this.treeData = this.$util.toTreeData({
              data: list,
              idField: 'id',
              parentIdField: 'parentId'
            });
          })
          .catch((e) => {});
      },

      async getInfo() {
        const res = await getAssetInfo(this.id);
        if (res) {
          if (!res.workstation) {
            res.workstation = {};
          }
          this.info = res;
          this.$set(this.info, 'location', res.deviceLocationName.split(',')); //位置信息
          this.$set(this.info, 'category', res.category);
          this.itemForm.addList = this.info.extInfoSelf
            ? this.info.extInfoSelf
            : [];
          // 设备图片
          this.imageUrl = res.imageUrl ? res.imageUrl : {};
          const rep = await getDetails(res.categoryId);
          console.log('rep------------------------');
          console.log(rep);
          this.$nextTick(() => {
            this.$refs.basicInfoRef.getDetailInfoAugr(rep.category);
            this.$refs.warehouseConfigRef.getDetailInfoAugr(rep.categoryWms);
            this.$refs.productInfoRef.getDetailInfoAugr(rep.categoryMes);
            this.$refs.planRef.getDetailInfoAugr(rep.categoryAps);
            this.$refs.qualityConfigRef.getDetailInfoAugr(rep.categoryQms);
            this.$refs.footerVueRef.getDetailInfoAugr(rep.category);
          });
          this.categoryVehicle = {
            ...rep.categoryVehicle,
            materialQuality: await sysDict(
              '周转车材质',
              rep.categoryVehicle.materialQuality
            )
          };
        }
      },

      // 删除自定义参数
      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条');
        }
      },

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

      // 点击确定保存
      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,
          imageUrl: this.imageUrl || {},
          extInfoSelf: extendField,
          ownershipGroupId: this.info.ownershipGroupId,
          rootCategoryLevelId: this.info.rootCategoryLevelId,
          categoryId: this.info.categoryId,
          deviceLocationName: this.info.location
            ? this.info.location.join(',')
            : '',
          positionIds: '1,1,1,1',
          position: {
            type: '1',
            num: 1
          }
          // positionIds: typeof this.info.category.categoryLevelPathId == 'string'? this.info.category.categoryLevelPathId : JSON.parse(this.info.category.categoryLevelPathId).join(',')
        };
        //============================
        params.extInfo = {
          ownershipGroupId: this.info.ownershipGroupId,
          fixCode: this.info.fixCode,
          codeNumber: this.info.codeNumber
        };
        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;
          }
        });
      }

      // //使用说明书
      // operatingManual (info) {
      //   if (info.length > 0) {
      //     console.log(info, '------info-----')
      //     this.formData.operatingManual = info[0]
      //     console.log(this.formData.operatingManual, 'getImgs')
      //   } else {
      //     this.formData.operatingManual = null
      //     console.log(this.formData.operatingManual, 'getImgs')
      //   }
      // },
      // productionLicence (info) {
      //   this.formData.productionLicence = info[0]
      // },
      // explosionProofCertificate (info) {
      //   this.formData.explosionProofCertificate = info[0]
      // },
      // surveyReport (info) {
      //   this.formData.surveyReport = info[0]
      // },
      // inspectionCycleManual (info) {
      //   this.formData.inspectionCycleManual = info[0]
      // },
      // informationDrawing (info) {
      //   this.formData.informationDrawing = info[0]
      // },
      // productCertificate (info) {
      //   this.formData.productCertificate = info[0]
      // }
    }
  };
</script>

<style lang="scss" scoped>
  .equipment-container {
    background-color: #fff;
    padding: 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;
    }
    .basic-details-title:first-child {
      margin: 0px 0px 15px;
    }
    .content {
      padding: 0 20px;
    }
    .label-none {
      .el-form-item__content {
        margin-left: 0 !important;
      }
    }
    .upload-container {
      display: flex;
      align-items: center;
      justify-content: center;
      // .file-list {
      //   margin-left: 50px;
      //   flex: 1;
      // }
    }
    .el-form-item__content {
      display: flex;
    }
    .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>
