<template>
  <div>
    <el-drawer
      title=""
      :visible.sync="drawer"
      :custom-class="isFullscreen ? 'not-fullscreen' : 'is-fullscreen'"
      :before-close="handleClose"
      :with-header="false"
    >
      <!-- 自定义头部 -->
      <div class="custom-drawer-header" v-if="!isWt">
        <div class="radio_box rx-cc">
          <el-radio-group
            size="small"
            v-model="currentNodeData.bomType"
            @change="bomChange"
          >
            <el-radio-button :label="4">EBOM </el-radio-button>
            <el-radio-button :label="1">PBOM </el-radio-button>
            <el-radio-button
              :label="2"
              v-if="
                searchObj.isProduct ||
                [1, 9].includes(searchObj.rootPathIdParent)
              "
              >MBOM
            </el-radio-button>
            <el-radio-button
              :label="3"
              v-if="
                searchObj.isProduct ||
                [1, 9].includes(searchObj.rootPathIdParent)
              "
              >ABOM
            </el-radio-button>
          </el-radio-group>
        </div>
        <div>
          <el-button
            type="text"
            style="color: #f56c6c"
            v-if="isNotData && currentNodeData.approvalStatus == 3"
            :underline="false"
          >
            {{ approvalStatusOpt[+currentNodeData.approvalStatus] }}
          </el-button>

          <el-button
            icon="el-icon-full-screen"
            type="text"
            @click="handleFull"
            >{{ isFullscreen ? '全屏' : '缩小' }}</el-button
          >
          <el-button
            icon="el-icon-circle-close"
            type="text"
            @click="handleClose"
            >关闭</el-button
          >
        </div>
      </div>

      <!-- 抽屉内容 -->
      <div class="drawer_content">
        <ele-split-layout
          width="260px"
          allow-collapse
          :resizable="true"
          :min-size="200"
          :max-size="-200"
          :left-style="{
            overflow: 'hidden',
            width: '100%'
          }"
          :right-style="{ overflow: 'hidden' }"
          :responsive="false"
        >
          <div class="ele-border-lighter sys-organization-list">
            <div>
              版本号: &nbsp; &nbsp;
              <el-select
                size="mini"
                style="width: 72%; margin: 6px 0"
                v-model="searchObj.versions"
                placeholder="请选择bom版本"
                @change="getTreeData"
                :disabled="isWt"
              >
                <el-option
                  v-for="item in versList"
                  :label="'V' + item.versions + '.0'"
                  :value="item.versions"
                  :key="item.id"
                >
                </el-option>
              </el-select>
            </div>

            <el-tree
              class="treeData"
              :data="treeList"
              :expand-on-click-node="false"
              :props="defaultProps"
              ref="treeRef"
              :default-expanded-keys="current && current.id ? [current.id] : []"
              :highlight-current="true"
              node-key="id"
              @node-click="handleNodeClick"
            >
              <span class="custom-tree-node" slot-scope="{ node, data }">
                {{ node.label }} / {{ data.code }}
              </span>
            </el-tree>
          </div>

          <template v-slot:content v-if="isNotData">
            <el-tabs
              v-model="activeName"
              class="tab-box"
              type="border-card"
              @tab-click="handleClick"
            >
              <el-tab-pane label="属性" name="属性">
                <attribute
                  :attributeData="currentNodeData"
                  :codes="searchObj.code"
                ></attribute>
              </el-tab-pane>

              <el-tab-pane
                :label="
                  currentNodeData.bomType == 1
                    ? 'PBOM明细表'
                    : currentNodeData.bomType == 2
                    ? 'MBOM明细表'
                    : ''
                "
                name="明细表"
              >
                <detailedList
                  v-if="activeName == '明细表'"
                  :isTemp="searchObj.isTemp"
                  :attributeData="currentNodeData"
                  :treeId="treeId"
                  :codes="searchObj.code"
                ></detailedList>
              </el-tab-pane>
            </el-tabs>
          </template>

          <template v-slot:content v-else>
            <el-empty
              :image-size="200"
              :description="
                currentNodeData.bomType == 1
                  ? 'PBOM 暂无数据，请先新建'
                  : currentNodeData.bomType == 2
                  ? 'MBOM 暂无数据，请先新建'
                  : currentNodeData.bomType == 3
                  ? 'ABOM 暂无数据，请先新建'
                  : 'EBOM 暂无数据，请先新建'
              "
            ></el-empty>
          </template>
        </ele-split-layout>
      </div>
    </el-drawer>
  </div>
</template>

<script>
  import {
    getBomTreeList,
    versionList,
    getBomGetById,
    convert,
    convertABom,
    convertEBOM,
    convertEBomToPBOM,
    deleteBomTreeList,
    bomSubmit,
    jsBomSubmit,
    deviceBomSubmit,
    hasNewVersion
  } from '@/api/material/BOM.js';

  import attribute from './components/attribute.vue';
  import detailedList from './components/detailedList.vue';

  export default {
    components: {
      attribute,
      detailedList
    },
    data() {
      return {
        drawer: false,
        isFullscreen: true,

        currentNodeData: {
          bomType: 1,
          children: []
        },

        current: {},
        treeList: [],
        versList: [],
        treeLoading: false,

        defaultProps: {
          children: 'children',
          label: 'name'
        },

        searchObj: {
          versions: '',
          categoryId: '',
          isProduct: false,
          isTemp: 0
        },

        activeName: '属性',
        isNotData: true,

        moudleName: 'mainUser',
        isSubmit: false,
        radioSubmit: 1,

        treeId: null,

        approvalStatusOpt: {
          0: '未提交',
          1: '审核中',
          2: '审核通过',
          3: '审核不通过'
        },

        isWt: false
      };
    },

    computed: {
      clientEnvironmentId() {
        return this.$store.state.user.info.clientEnvironmentId;
      }
    },

    methods: {
      open(row) {
        this.searchObj = row;

        if (Object.prototype.hasOwnProperty.call(row, 'isWt') && row.isWt) {
          this.isWt = row.isWt;
          this.isFullscreen = false;
        }

        if (Object.prototype.hasOwnProperty.call(row, 'bomType')) {
          this.currentNodeData.bomType = row.bomType;
        }
        this.drawer = true;
        this.getTreeData();
        this.getVersion();
      },

      handleClose() {
        this.searchObj = {
          versions: '',
          categoryId: '',
          isProduct: false,
          isTemp: 0
        };
        this.activeName = '属性';
        this.drawer = false;
      },

      handleFull() {
        this.isFullscreen = !this.isFullscreen;
        this.$forceUpdate();
      },

      bomChange(e) {
        console.log(e);
        this.searchObj.versions = '';
        this.currentNodeData.bomType = e;

        this.getTreeData();
        this.getVersion();
      },

      async getTreeData() {
        try {
          this.treeLoading = true;

          const res = await getBomTreeList({
            categoryId: this.searchObj.categoryId,
            versions: this.searchObj.versions,
            bomType: this.currentNodeData.bomType,
            isTemp: this.searchObj.isTemp || 0
          });
          this.treeLoading = false;
          if (res?.code === '0') {
            if (res.data?.length > 0) {
              this.treeList = res.data;
              this.$nextTick(() => {
                this.isNotData = true;
                // 默认高亮第一个
                this.$refs.treeRef.setCurrentKey(res.data[0].id);
                this.handleNodeClick(res.data[0]);
              });
            } else {
              this.isNotData = false;
              this.treeList = [];
            }
            return this.treeList;
          }
        } catch (error) {
          console.log(error);
        }
        this.treeLoading = false;
      },

      handleNodeClick(data) {
        this.treeId = data.id;
        this.handBomDetails(data.id);
      },

      handBomDetails(id) {
        if (id) {
          getBomGetById(id).then((res) => {
            this.currentNodeData = res.data;
            this.searchObj.versions = this.currentNodeData.versions;
            this.$forceUpdate();
          });
        } else {
          this.currentNodeData = {
            bomType: 1,
            children: []
          };
        }
      },

      getVersion(type) {
        let param = {
          categoryId: this.searchObj.categoryId,
          bomType: this.currentNodeData.bomType,
          isTemp: this.searchObj.isTemp || 0
        };
        versionList(param).then((res) => {
          this.versList = res || [];
          if (type == 'del' || type == 'add') {
            if (this.versList.length >= 1) {
              this.searchObj.versions =
                this.versList[this.versList.length - 1].versions;
            } else {
              this.searchObj.versions = '';
            }

            this.getTreeData();
          }
        });
      },

      handleClick(tab) {},

      async transformation(tt) {
        if (this.currentNodeData.status != 1) {
          return this.$message.warning('只有已发布版本才可以转换');
        }

        let _type = tt == 'P' ? 1 : tt == 'M' ? 2 : tt == 'A' ? 3 : 4;
        if (!this.isEdit) {
          let isHas = await this.hasVersionFn(_type);
          if (!isHas) return;
        }

        this.loadingInstance = this.$loading({
          lock: true,
          text: '转换中...',
          background: 'rgba(0, 0, 0, 0.7)'
        });
        let ULR =
          tt == 'M'
            ? convert
            : tt == 'A'
            ? convertABom
            : tt == 'E'
            ? convertEBOM
            : tt == 'P'
            ? convertEBomToPBOM
            : '';
        ULR({
          versions: this.searchObj.versions,
          categoryId: this.searchObj.categoryId
        }).then((data) => {
          if (data.code == '0') {
            this.loadingInstance.close();
            this.$message.success('转换成功');

            this.currentNodeData.bomType = _type;
            this.getTreeData();
            this.getVersion();
          }
        });
      },

      async hasVersionFn(bomType) {
        return new Promise((resolve) => {
          let param = {
            categoryId: this.searchObj.categoryId,
            bomType: bomType
          };
          hasNewVersion(param).then((res) => {
            if (res.data == 1) {
              this.$confirm('已经草稿版本存在，是否覆盖?', '提示', {
                confirmButtonText: '覆盖',
                cancelButtonText: '取消',
                type: 'warning'
              })
                .then(() => {
                  resolve(true);
                })
                .catch(() => {
                  resolve(false);
                });
            } else {
              resolve(true);
            }
          });
        });
      }
    }
  };
</script>

<style lang="scss" scoped>
  /* 自定义全屏样式 */
  ::v-deep .is-fullscreen {
    width: 100vw !important;
    height: 100vh !important;
    overflow: hidden !important; /* 隐藏滚动条 */
  }
  ::v-deep .not-fullscreen {
    width: calc(100vw - 260px) !important;
    height: 100vh !important;
    overflow: hidden !important; /* 隐藏滚动条 */
  }

  .custom-drawer-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 4px 15px;
    background-color: #f5f7fa; /* 自定义背景色 */
    border-bottom: 1px solid #ebeef5; /* 自定义边框，与抽屉内容分隔 */
  }

  .drawer_content {
    margin: 10px 20px;
    box-sizing: border-box;
  }
  .sys-organization-list {
    height: calc(100vh - 65px);
    box-sizing: border-box;
    border-width: 1px;
    border-style: solid;
    overflow: auto;
    padding: 0 10px;
    box-sizing: border-box;
    display: flex;
    flex-direction: column;
    overflow: hidden;

    .treeData {
      height: 0 1 auto;
      overflow-y: auto;
    }
  }

  .tab-box {
    margin-top: 12px;
  }
</style>
