<template>
  <div class="ele-body">
    <el-card shadow="never">
      <div class="page-title">
        <el-page-header @back="goBack">
          <div slot="content" class="pageContent">
            <div>{{ pageTitle }}</div>
            <el-form class="topform">
              <el-form-item label="物品类型" label-width="70px">
                <el-select
                  v-model="defaultNum"
                  placeholder="请选择"
                  :disabled="uneditable"
                >
                  <el-option
                    v-for="item in typeList"
                    :key="item.id"
                    :label="item.value"
                    :value="item.code"
                    @click.native="chooseItem(item)"
                  >
                  </el-option>
                </el-select>
              </el-form-item>
            </el-form>
          </div>
        </el-page-header>
      </div>
      <div class="table-container">
        <div class="tree-col">
          <ItemForm
            ref="itemFormRef"
            :itemForm="itemForm"
            :prefix="prefix"
            :defaultNum="defaultNum"
          />
        </div>
        <div class="attribute-row">
          <RowForm
            ref="customFormRef"
            :itemForm="itemForm"
            :defaultNum="defaultNum"
          />
          <div
            class="row-table"
            v-if="defaultNum != '8' && defaultNum != '2' && defaultNum != '5'"
          >
            <ItemMatch
              ref="itemMatchRef"
              :defaultNum="defaultNum"
              :typeList="typeList"
            ></ItemMatch>
          </div>
          <div class="page-footer-btn mt20">
            <el-button @click="goBack">取消</el-button>
            <el-button type="primary" @click="submit">确定</el-button>
          </div>
        </div>
      </div>
    </el-card>
  </div>
</template>

<script>
  import ItemForm from './components/ItemForm';
  import RowForm from './components/RowForm';
  import ItemMatch from './components/item-match';
  import dictMixins from '@/mixins/dictMixins';
  import {
    informationAdd,
    getDetails,
    informationEdit
  } from '@/api/classifyManage/itemInformation';
  import { getCode } from '@/api/codeManagement';
  export default {
    components: { ItemForm, RowForm, ItemMatch },
    mixins: [dictMixins],
    data () {
      return {
        pageTitle: '',
        itemForm: {
          categoryLevelPathId: [],
          addList: [],
          info: {
            angle: 'notA'
          },
          unpack: 0,
          urlIdList: [],
          univalenceUnit: 'yuan',
          expirationDateUnit: 'minute',
          takeStockPattern: 1
        },
        defaultNum: '1',
        selectNode: null,
        classList: [],
        changeData: [],
        urlIdList: [],
        requestData: {},
        uneditable: false,
        newCode: ''
      };
    },
    computed: {
      prefix () {
        const obj =
          (this.dict[this.dictEnum['分类编号']] || []).find(
            (itm) => itm.dictCode === this.defaultNum
          ) || {};
        return obj && obj.dictValue;
      },
      typeList () {
        const noList = this.dict[this.dictEnum['分类编号']] || [];

        return (this.dict[this.dictEnum['类型用途']] || []).map((item) => {
          const obj =
            noList.find((itm) => itm.dictCode === item.dictCode) || {};
          return {
            ...item,
            value: `${obj.dictValue} ${item.dictValue}`,
            name: item.dictValue,
            prefix: obj.dictValue,
            code: item.dictCode
          };
        });
      }
    },
    async created () {
      await this.requestDict('分类编号');
      await this.requestDict('类型用途');
      this.pageTitle = this.$route.query.pageTitle;
      if (this.pageTitle == '新建物品') {
        this.selectNode = JSON.parse(this.$route.query.selectNode);
        console.log('selectNode', this.selectNode);
        if (this.selectNode) {
          this.itemForm.categoryLevelPathId = this.selectNode.id;
          if (this.selectNode.id != '0') {
            this.defaultNum = this.selectNode.type;
            this.setDefault(this.defaultNum);
          }
          this.itemForm.urlIdList = this.selectNode.urlIdList;
        }
      } else {
        this.getDetilInfo(this.$route.query.id);
      }
      if (this.pageTitle == '编辑物品') {
        this.uneditable = true;
      } else {
        this.uneditable = false;
        this.getOrderCode();
      }
    },
    methods: {
      async getOrderCode () {
        const data = await getCode('material_management');
        this.newCode = data;
        this.$set(this.itemForm, 'itemCode', data);
      },

      // 在 Input 值改变时触发
      handleEdit (e) {
        let value = e.replace(/^(0+)|[^\d]+/g, ''); // 以0开头或者输入非数字，会被替换成空
        value = value.replace(/(\d{15})\d*/, '$1'); // 最多保留15位整数
      },
      goBack () {
        this.$router.go(-1);
      },

      // 获取详情
      async getDetilInfo (id) {
        const data = await getDetails(id);
        this.chooseItem({ code: data.type });
        this.itemForm = data;
        if (data.univalence) {
          this.$set(this.itemForm, 'univalence', data.univalence);
        } else {
          this.$set(this.itemForm, 'univalence', 'null');
        }
        if (data.expirationDate) {
          this.$set(this.itemForm, 'expirationDate', data.expirationDate);
        } else {
          this.$set(this.itemForm, 'expirationDate', 'null');
        }
        this.$set(
          this.itemForm,
          'info',
          data.extendField ? JSON.parse(data.extendField) : { angle: 'notA' }
        );
        this.$set(this.itemForm, 'name', data.name);
        this.$set(
          this.itemForm,
          'addList',
          data.selfDefinedParameter ? JSON.parse(data.selfDefinedParameter) : []
        );
        this.itemForm.urlIdList = data.categoryLevelPathId
          ? JSON.parse(data.categoryLevelPathId)
          : [];
        if (this.pageTitle == '编辑物品') {
          // this.itemForm.itemCode = data.code.substring(3)
          this.$set(this.itemForm, 'itemCode', data.code.substring(3));
        } else {
          this.$set(this.itemForm, 'isCitation', false);
          this.$set(this.itemForm, 'itemCode', this.newCode);
        }
        this.$set(this.itemForm, 'unpack', data.unpack);
        // this.itemForm.isTransferAssets = data.isTransferAssets
        //   ? 'true'
        //   : 'false';
        for (const key in this.itemForm.categoryVoRelationMap) {
          this.$refs.itemMatchRef &&
            this.$refs.itemMatchRef.matchList(
              key,
              this.itemForm.categoryVoRelationMap
            );
        }

        console.log(this.itemForm, 'itemForm');
      },

      // 改变物品类型
      chooseItem (item) {
        this.defaultNum = item.code;
        this.initItemForm();
        this.$refs.itemFormRef.$refs.formName.resetFields();
        this.getOrderCode();
        this.itemForm.type = item.code;
        this.selectNode = null;
        this.setDefault(item.code);
      },

      submit () {
        const a1 = new Promise((resolve, reject) => {
          this.$refs.itemFormRef.validateForm((valid) => {
            if (valid) resolve();
          });
        });
        const a2 = new Promise((resolve, reject) => {
          this.$refs.customFormRef.validateForm((valid) => {
            if (valid) resolve();
          });
        });
        Promise.all([a1, a2]).then(() => {
          this.$refs.itemMatchRef && this.$refs.itemMatchRef.mapAddList();

          this.requestData = this.itemForm;
          const { pathName, pathId } = this.$refs.itemFormRef.getText();
          this.requestData.categoryLevelPath = pathName;
          this.requestData.categoryLevelId = pathId;
          this.requestData.type = this.defaultNum;
          this.requestData.selfDefinedParameter = JSON.stringify(
            this.requestData.addList
          );
          this.requestData.extendField = JSON.stringify(this.requestData.info);
          this.requestData.code = this.prefix + this.requestData.itemCode;
          this.requestData.classificationCode = this.defaultNum;
          this.requestData.categoryLevelPathId = JSON.stringify(
            this.requestData.urlIdList
          );
          this.requestData.expirationDate = this.itemForm.expirationDate
            ? this.itemForm.expirationDate
            : null;
          this.requestData.univalence = this.itemForm.univalence
            ? this.itemForm.univalence
            : null;
          this.requestData.categoryRelationPoList = (
            (this.$refs.itemMatchRef && this.$refs.itemMatchRef.getMapList()) ||
            []
          ).map((i) => ({
            ...i,
            categoryId: i.id,
            mainCategoryId: this.$route.query.id || ''
          }));

          //不传报错
          this.requestData.iotProductSchema = '{}';
          if (this.pageTitle == '编辑物品') {
            this.requestData.id = this.$route.query.id;
            delete this.requestData.categoryVoRelationMap;
            this.$confirm(
              '参数信息有变更，与当前已存在的台账信息参数不一致，确定后将同步已存在的台账信息参数 !',
              '重要提示！',
              {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning',
                center: true
              }
            )
              .then(() => {
                informationEdit(this.requestData).then((res) => {
                  this.$message.success('物品编辑成功');
                  this.$router.push({
                    path: '/classifyManage/itemInformation'
                  });
                });
              })
              .catch(() => {});
          } else {
            informationAdd(this.requestData).then((res) => {
              this.$message.success('物品新增成功');
              this.$router.push({
                path: '/classifyManage/itemInformation'
              });
            });
          }
        });
      },

      convertTreeData (data) {
        this.changeData = data;
        for (let i = 0; i < this.changeData.length; i++) {
          if (this.changeData[i].children != undefined) {
            const temp = this.changeData[i].children;
            delete this.changeData[i].children;
            this.changeData = this.changeData.concat(temp);
          }
        }
      },

      setDefault (val) {
        this.$refs.itemMatchRef && this.$refs.itemMatchRef.setDefault(val);
      },

      initItemForm () {
        this.itemForm = {
          categoryLevelPathId: [],
          addList: [],
          info: { angle: 'notA' },
          urlIdList: [],
          univalenceUnit: 'yuan',
          expirationDateUnit: 'minute',
          takeStockPattern: 1
        };
      }
    }
  };
</script>

<style lang="scss" scoped>
  .ele-body {
    :deep(.page-title) {
      border-bottom: 1px solid #eaeefb;
      padding-bottom: 8px;
      margin-bottom: 16px;
      display: flex;
      align-items: center;
      .el-page-header__left {
        display: flex;
        align-items: center;
      }
      .pageContent {
        display: flex;
        align-items: center;
        font-size: 18px;
        color: #303133;
        .topform {
          // margin: 5px 0 0 30px;
          margin-left: 30px;
          display: flex;
          align-items: center;

          .el-form-item {
            margin-bottom: 0;
          }
        }
      }
    }
    .table-container {
      flex: 1;
      display: flex;
      overflow: hidden;
      .tree-col {
        margin-right: 10px;
        width: 30%;
        min-width: 250px;
        overflow: auto;
        padding: 20px 20px 20px 0px;
        background-color: #fff;
        margin-top: 10px;
        border: 1px solid #e6ebf5;
        border-radius: 4px;
        box-shadow: 0 2px 12px 0 rgb(0 0 0 / 10%);
      }
    }

    :deep(.attribute-row) {
      padding: 20px 5px;
      background: #fff;
      margin-top: 10px;
      overflow: auto;
      width: 70%;
      border: 1px solid #e6ebf5;
      border-radius: 4px;
      box-shadow: 0 2px 12px 0 rgb(0 0 0 / 10%);
      position: relative;
      .row-table {
        width: 100%;
        margin: 20px auto 80px;
        .table-box {
          width: 100%;
          margin: 10px auto;
          // max-height:400px;
          // overflow-y: auto;
        }
        .bom-top {
          width: 100%;
          display: flex;
          align-items: center;
          justify-content: flex-start;
          .top-input {
            margin-left: 20px;
            display: flex;
            align-items: center;
            justify-content: flex-start;
            .input-box {
              width: 150px;
              margin: 0 10px;
            }
          }
        }
      }
      .page-footer-btn {
        background: #fff;
        z-index: 1;
        position: absolute;
        bottom: 20px;
        right: 0px;
        text-align: right;
        width: 100%;
        border-top: 1px solid #e6ebf5;
        padding: 20px 20px 0 0;
      }
    }
  }
</style>
