<template>
  <div>
    <el-drawer
      title=""
      :visible.sync="drawer"
      :custom-class="isFullscreen ? 'not-fullscreen' : 'is-fullscreen'"
      :before-close="handleClose"
      :with-header="false"
      :append-to-body="true"
    >
      <!-- 自定义头部 -->
      <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"
              v-permissionccc="['main:bomcategory:ebom']"
              >EBOM
            </el-radio-button>
            <el-radio-button :label="1">PBOM </el-radio-button>

            <!-- v-if="
                searchObj.isProduct ||
                [1, 9].includes(searchObj.rootPathIdParent)
              " -->
            <el-radio-button
              :label="2"
              v-permissionccc="['main:bomcategory:mbom']"
              >MBOM
            </el-radio-button>
            <el-radio-button
              :label="3"
              v-permissionccc="['main:bomcategory:abom']"
              >ABOM
            </el-radio-button>
          </el-radio-group>

          <div style="margin-left: 100px">
            <el-button
              type="primary"
              size="mini"
              icon="el-icon-plus"
              @click="handleAdd"
              v-if="
                $hasPermission('main:categoryparam:saveBom') &&
                currentNodeData.bomType == 1 &&
                (currentNodeData.parentId == '0' || !currentNodeData.parentId)
              "
            >
              新建
            </el-button>

            <el-button
              type="danger"
              size="mini"
              icon="el-icon-delete"
              @click="remove"
              v-if="
                (currentNodeData.approvalStatus == 0 ||
                  currentNodeData.approvalStatus == 3) &&
                $hasPermission('main:categoryparam:deleteBom') &&
                (currentNodeData.parentId == '0' || !currentNodeData.parentId)
              "
            >
              删除
            </el-button>

            <el-button
              v-if="
                currentNodeData.bomType == 1 &&
                (currentNodeData.parentId == '0' || !currentNodeData.parentId)
              "
              type="primary"
              size="mini"
              icon="el-icon-download"
              plain
              >导出</el-button
            >

            <el-button
              @click="uploadFile"
              v-if="
                currentNodeData.bomType == 1 &&
                (currentNodeData.parentId == '0' || !currentNodeData.parentId)
              "
              type="primary"
              size="mini"
              icon="el-icon-upload2"
              plain
              >导入</el-button
            >

            <el-button
              type="primary"
              size="mini"
              icon="el-icon-refresh"
              plain
              @click="transformation('P')"
              :disabled="currentNodeData.approvalStatus != 2"
              v-if="
                currentNodeData.bomType == 4 &&
                (currentNodeData.parentId == '0' || !currentNodeData.parentId)
              "
              >转换PBOM</el-button
            >

            <el-button
              type="primary"
              size="mini"
              icon="el-icon-refresh"
              plain
              :disabled="currentNodeData.approvalStatus != 2"
              @click="transformation('E')"
              v-if="
                currentNodeData.bomType == 1 &&
                (currentNodeData.parentId == '0' || !currentNodeData.parentId)
              "
              >转换EBOM</el-button
            >

            <el-button
              type="primary"
              size="mini"
              icon="el-icon-refresh"
              plain
              :disabled="currentNodeData.approvalStatus != 2"
              @click="transformation('M')"
              v-if="
                currentNodeData.bomType == 1 &&
                (searchObj.isProduct ||
                  ['1', '9'].includes(searchObj.rootPathIdParent)) &&
                (currentNodeData.parentId == '0' || !currentNodeData.parentId)
              "
              >转换MBOM</el-button
            >

            <el-button
              type="primary"
              size="mini"
              icon="el-icon-refresh"
              plain
              :disabled="currentNodeData.approvalStatus != 2"
              @click="transformation('A')"
              v-if="
                currentNodeData.bomType == 1 &&
                (searchObj.isProduct ||
                  ['1', '9'].includes(searchObj.rootPathIdParent)) &&
                (currentNodeData.parentId == '0' || !currentNodeData.parentId)
              "
              >转换ABOM</el-button
            >

            <el-button
              type="primary"
              size="mini"
              @click="handSubmit"
              v-if="
                (currentNodeData.approvalStatus == 0 ||
                  currentNodeData.approvalStatus == 3) &&
                (currentNodeData.parentId == '0' || !currentNodeData.parentId)
              "
            >
              提交发布
            </el-button>

            <el-button
              type="primary"
              size="mini"
              @click="handleRefresh"
              v-if="currentNodeData.approvalStatus != 1"
            >
              刷新
            </el-button>
          </div>
        </div>
        <div>
          <el-button
            type="text"
            @click="handleDetails()"
            v-if="isNotData && currentNodeData.approvalStatus == 1"
            :underline="false"
          >
            {{ approvalStatusOpt[+currentNodeData.approvalStatus] }}
          </el-button>

          <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"
        >
          <!-- // tree 组件 -->
          <div class="ele-border-lighter sys-organization-list">
            <div>
              版本号: &nbsp; &nbsp;
              <el-select
                size="mini"
                style="width: 70%; 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>
              <br />
              属性类型:
              <el-select
                size="mini"
                style="width: 70%; margin: 6px 0"
                v-model="searchObj.componentAttribute"
                filterable
                multiple
                placeholder="请选择属性类型"
                @change="getTreeData"
                :disabled="isWt"
              >
                <el-option
                  v-for="item in sxtList"
                  :key="item.value"
                  :value="item.value"
                  :label="item.label"
                ></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 }">
                {{ data.categoryCode }} / {{ node.label }}
              </span>
            </el-tree>
          </div>

          <template v-slot:content v-if="isNotData">
            <!-- 基本信息 -->
            <baseInfo
              :dataInfo="currentNodeData"
              @getNewBomData="getNewBomData"
            />

            <!-- table -->
            <el-tabs
              v-model="activeName"
              class="tab-box"
              type="border-card"
              @tab-click="handleClick"
            >
              <el-tab-pane label="属性" name="属性">
                <attribute
                  :attributeData="currentNodeData"
                  :isWt="isWt"
                ></attribute>
              </el-tab-pane>

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

              <el-tab-pane
                label="工艺路线"
                name="工艺路线"
                v-if="currentNodeData.bomType != 4"
              >
                <routing
                  v-if="activeName == '工艺路线'"
                  ref="routingRef"
                  :isWt="isWt"
                  :attributeData="currentNodeData"
                  :taskParam="currentNodeData"
                  :resourceBomId="resourceBomId"
                ></routing>
              </el-tab-pane>
              <el-tab-pane
                label="工序配置"
                name="工序配置"
                v-if="currentNodeData.bomType != 4"
              >
                <!-- && (searchObj.isProduct ||
              [1, 9].includes(searchObj.rootPathIdParent)) -->
                <workmanship
                  v-if="activeName == '工序配置'"
                  ref="workmanshipRef"
                  :attributeData="currentNodeData"
                  :taskParam="currentNodeData"
                  :resourceBomId="resourceBomId"
                ></workmanship>
              </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>

    <baseInfoSave
      v-if="baseInfoShow"
      @close="baseClose"
      :categoryObj="currentNodeData"
      :categoryId="searchObj.categoryId"
      :categoryName="searchObj.categoryName"
    ></baseInfoSave>

    <importDialog
      :defModule="moudleName"
      ref="importDialogRef"
      @success="getTreeData"
    />

    <el-dialog
      title="发布"
      :visible.sync="isSubmit"
      v-if="isSubmit"
      width="30%"
      center
    >
      <div>
        <el-radio v-model="radioSubmit" :label="1">药品</el-radio>
        <el-radio v-model="radioSubmit" :label="2">器械</el-radio>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="isSubmit = false">取 消</el-button>
        <el-button type="primary" @click="handJsSubmit()">确 定</el-button>
      </span>
    </el-dialog>

    <LCdetail ref="detailRef"></LCdetail>
  </div>
</template>

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

  import baseInfo from './baseInfo.vue';
  import baseInfoSave from './baseInfoSave.vue';
  import attribute from './attribute.vue';
  import detailedList from './detailedList.vue';
  import importDialog from '../qualityTesting/import-dialog.vue';
  import LCdetail from './LCdetail.vue';
  import routing from './routing.vue';
  import workmanship from './workmanship.vue';

  export default {
    name: 'bomDetailsPop',
    components: {
      baseInfo,
      baseInfoSave,
      attribute,
      detailedList,
      importDialog,
      LCdetail,
      routing,
      workmanship
    },
    data() {
      return {
        drawer: false,
        isFullscreen: true,
        resourceBomId: '',
        currentNodeData: {
          bomType: 1,
          children: [],
          parentId: ''
        },

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

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

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

        activeName: '属性',

        baseInfoShow: false,
        isNotData: true,

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

        treeId: null,

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

        sxtList: [
          {
            label: '自制件',
            value: 1
          },
          {
            label: '采购件',
            value: 2
          },
          {
            label: '外协件',
            value: 3
          },
          {
            label: '受托件',
            value: 4
          }
        ],

        isWt: false
      };
    },

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

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

        console.log(row, 'rowrowrowrowrow');

        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;

        if (
          this.currentNodeData.bomType == 2 ||
          this.currentNodeData.bomType == 3
        ) {
          this.searchObj.componentAttribute = [1];
        } else {
          this.searchObj.componentAttribute = [];
        }

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

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

      getNewBomData(data) {
        let rowData = {
          categoryId: data.categoryId,
          categoryName: data.name,
          code: data.code,
          versions: data.resourceBomVersion,
          rootPathIdParent: data.categoryLevelPathIdParent,
          isProduct: true,
          bomType: Number(data.bomType),
          isTemp: data.isTemp
        };
        this.open(rowData);
      },

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

      bomChange(e) {
        this.searchObj.versions = '';
        this.searchObj.componentAttribute = [];
        this.currentNodeData.bomType = e;

        if (
          this.currentNodeData.bomType == 2 ||
          this.currentNodeData.bomType == 3
        ) {
          this.searchObj.componentAttribute = [1];
        } else {
          this.searchObj.componentAttribute = [];
        }

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

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

          let componentAttribute = '';

          console.log(this.searchObj.componentAttribute);

          if (
            this.searchObj.componentAttribute &&
            this.searchObj.componentAttribute.length != 0
          ) {
            componentAttribute = this.searchObj.componentAttribute.join(',');
          }

          const res = await getBomTreeList({
            categoryId: this.searchObj.categoryId,
            versions: this.searchObj.versions,
            bomType: this.currentNodeData.bomType,
            isTemp: this.searchObj.isTemp || 0,
            componentAttribute
          });
          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.resourceBomId =
          data.parentId != 0 ? data.resourceBomId || data.id : data.id;
        this.handBomDetails(this.treeId);
      },

      handBomDetails(id) {
        if (id) {
          getBomGetById(id).then((res) => {
            res.data.attributeType = res.data.category.attributeType;

            this.currentNodeData = res.data;
            this.searchObj.versions = this.currentNodeData.versions;

            this.$forceUpdate();

            console.log(this.currentNodeData, 'this.currentNodeData');
          });
        } 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) {},
      remove() {
        if (this.currentNodeData.status == 1) {
          return this.$message.warning('已发布版本不能删除');
        }

        this.$confirm('是否确认删除?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
          .then(() => {
            deleteBomTreeList([this.currentNodeData.id]).then((msg) => {
              this.$message.success('删除' + msg);
              this.getVersion('del');
            });
          })
          .finally(() => {});
      },

      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.searchObj.versions = '';
              this.getTreeData();
              this.getVersion();
            }
          })
          .catch((err) => {
            this.loadingInstance.close();
          });
      },

      handleAdd() {
        this.baseInfoShow = true;
      },

      baseClose(val) {
        if (val) {
          this.getVersion('add');
        }
        this.activeName = '属性';
        this.baseInfoShow = false;
      },

      uploadFile() {
        this.$refs.importDialogRef.open();
      },

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

      handSubmit() {
        if (this.clientEnvironmentId == 5) {
          this.isSubmit = true;
        } else {
          this.$alert('确定要发布吗?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          })
            .then(() => {
              bomSubmit({ businessId: this.currentNodeData.id }).then((res) => {
                if (res?.code == 0) {
                  this.$message.success('发布成功');
                  this.getTreeData();
                }
              });
            })
            .catch(() => {});
        }
      },

      handJsSubmit() {
        let URL = this.radioSubmit == 1 ? jsBomSubmit : deviceBomSubmit;
        this.$alert('确定要发布吗?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
          .then(() => {
            URL({ businessId: this.currentNodeData.id }).then((res) => {
              this.isSubmit = false;
              this.$message.success('发布成功');
              this.getTreeData();
            });
          })
          .catch(() => {});
      },

      handleDetails() {
        if (!this.currentNodeData.processInstanceId) {
          this.$message.info('未提交没有审核流程');
        } else {
          this.$refs.detailRef.open(this.currentNodeData.processInstanceId);
        }
      },

      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;
      height: calc(100vh - 125px);
    }
  }

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