<template>
  <!-- 公司管理 -->
  <div class="home">
    <actionBar :operateList="operateList" :formList="formList" :ruleForm="searchRuleForm" @openModel="openModel"
      @searchProtocol="searchProtocol"></actionBar>
    <div class="card_content">
      <!-- 表单 -->
      <treeTable :treeData="treeData" :treeDataList="treeDataList" @buttonData="buttonData"></treeTable>
      <!-- 分页 -->
      <div v-if="Total">
        <pagination :total="Total" :currentPage="Pagination.PageIndex" @changeSize="changeSize"
          @changeCurrent="changeCurrent">
        </pagination>
      </div>
    </div>
    <el-dialog :title="staffTitle" :visible.sync="staffDialogVisible" width="600px" :close-on-click-modal="false"
      @close="closeDialog">
      <forms ref="childRules" :formNewList="formRuleList" :ruleForm="ruleForm" labelWidth="150px"></forms>
      <span slot="footer" class="dialog-footer">
        <el-button plain @click="staffDialogVisible = false">取 消</el-button>
        <el-button type="primary" :loading="confirmLoading" @click="handleAdd">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 导入公司对话框 -->
    <el-dialog title="导入公司" :visible.sync="importDialogVisible" width="600px" :close-on-click-modal="false"
      @close="closeImportDialog">
      <div style="max-height: 500px; overflow-y: auto;">
        <el-tree
          ref="companyTree"
          :data="thirdTreeData"
          :props="treeProps"
          show-checkbox
          node-key="Id"
          :default-expand-all="true"
          :check-strictly="false"
          @check="handleTreeCheck">
        </el-tree>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button plain @click="importDialogVisible = false">取 消</el-button>
        <el-button type="primary" :loading="importLoading" @click="handleImport">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
  import {
    getCompany,
    getCompanyDetails,
    addCompany,
    putCompany,
    delCompany,
    getThirdTree,
    importThirdTree
  } from '@/api/company'
  import actionBar from '@/components/actionBar'
  import treeTable from '@/components/treeTable'
  import pagination from '@/components/pagination'
  import forms from '@/components/forms'
  import {
    formRules,
    employee
  } from "./company.js";
  export default {
    name: 'UserManagement',
    components: {
      actionBar,
      treeTable,
      pagination,
      forms,
    },
    data() {
      return {
        operateList: [{
          type: 'add',
          title: '添加公司',
          icon: 'el-icon-plus',
        }, {
          type: 'import',
          title: '导入公司',
          icon: 'el-icon-upload2',
        }],
        formList: [{
          type: 'input',
          label: '名称',
          field: 'name',
          placeholder: '名称',
        }],
        searchRuleForm: {
          name: '',
        },
        searchValue: {},
        Pagination: {
          PageIndex: 1,
          PageSize: 10,
        },
        Total: 0,
        operationType: '',
        tableList: employee(),
        tableData: [],
        staffTitle: '添加',
        staffDialogVisible: false,
        formRuleList: [],
        ruleForm: {
          name: '',
          appName: '',
          companyCoordinate: '',
          companyAddress: '',
          coldKey: '',
          isIceReleaseCold: false,
          isCoolerReleaseCold: false,
          isOutStorage: false,
          iceRaftManage: false,
          remark: '',
        },
        confirmLoading: false,

        treeData: employee(),
        treeDataList: [],
        parentId: null,
        // 导入公司相关
        importDialogVisible: false,
        thirdTreeData: [],
        treeProps: {
          children: 'Children',
          label: 'T_name'
        },
        selectedCompanyNodes: [],
        importLoading: false,
      }
    },
    mounted() {
      const dataList = formRules();
      this.formRuleList = dataList;
      this.getList()
    },
    methods: {
      // 搜索
      searchProtocol(value) {
        this.searchValue = value
        this.getList()
      },
      // 获取公司列表
      getList() {
        var params = {
          page: this.Pagination.PageIndex,
          pageSize: this.Pagination.PageSize,
          ...this.searchValue
        }
        getCompany(params).then(res => {
          if (res.code == 200) {
            this.treeDataList = res.data
            this.Total = res.data.count
          }
        })
      },
      // 弹窗表单添加
      handleAdd() {
        let flag = this.$refs['childRules'].validateForm();
        if (flag) {
          if (this.operationType == 'add' || this.operationType == 'subAdd') {
            this.confirmLoading = true
            var params = {
              ...this.ruleForm
            }
            if (this.operationType == 'subAdd') {
              params.parentId = this.parentId
            }
            addCompany(params).then(res => {
              if (res.code == 200) {
                this.$message({
                  message: '操作成功',
                  type: 'success'
                });
                this.getList()
              }
              this.staffDialogVisible = false
              this.confirmLoading = false
            }).catch(() => {
              this.confirmLoading = false
            })
          } else if (this.operationType == 'edit') {
            this.confirmLoading = true
            var params = {
              id: this.ruleForm.id,
              name: this.ruleForm.name,
              appName: this.ruleForm.appName,
              remark: this.ruleForm.remark,
              coldKey: this.ruleForm.coldKey,
              companyAddress: this.ruleForm.companyAddress,
              isIceReleaseCold: this.ruleForm.isIceReleaseCold,
              isCoolerReleaseCold: this.ruleForm.isCoolerReleaseCold,
              isOutStorage: this.ruleForm.isOutStorage,
              iceRaftManage: this.ruleForm.iceRaftManage,
            }
            putCompany(params).then(res => {
              if (res.code == 200) {
                this.$message({
                  message: '操作成功',
                  type: 'success'
                });
                this.getList()
              }
              this.staffDialogVisible = false
              this.confirmLoading = false
            }).catch(() => {
              this.confirmLoading = false
            })
          }
        } else {
          this.$message.error('表单信息不完整，请继续填写完整');
        }
      },
      buttonData(row, type) {
        this.operationType = type
        if (type == 'edit') {
          this.staffTitle = '编辑'
          this.staffDialogVisible = true
          setTimeout(() => {
            this.$nextTick(() => {
              this.ruleForm = JSON.parse(JSON.stringify(row))
            })
          })
        } else if (type == 'del') {
          this.deleteUser(row.id)
        } else if (type == 'subAdd') {
          this.staffTitle = '添加子级'
          this.staffDialogVisible = true
          this.parentId = row.id
        }
      },
      openModel(type) {
        if (type === 'import') {
          this.openImportDialog()
        } else {
          this.staffTitle = '添加'
          this.staffDialogVisible = true
          this.operationType = type
        }
      },
      // 打开导入公司对话框
      openImportDialog() {
        this.importDialogVisible = true
        this.thirdTreeData = []
        this.selectedCompanyNodes = []
        this.getThirdTreeData()
      },
      // 获取第三方公司树形结构
      getThirdTreeData() {
        getThirdTree().then(res => {
          if (res.code == 200) {
            this.thirdTreeData = res.data || []
          }
        }).catch(() => {
          this.$message.error('获取公司树形结构失败')
        })
      },
      // 树节点选择变化
      handleTreeCheck(data, checkedInfo) {
        // 保存选中的节点ID
        this.selectedCompanyNodes = checkedInfo.checkedKeys || []
      },
      // 处理导入
      handleImport() {
        const checkedKeys = this.$refs.companyTree.getCheckedKeys()
        if (checkedKeys.length === 0) {
          this.$message.warning('请至少选择一个公司')
          return
        }
        
        // 构建需要导入的数据结构
        const importData = this.buildImportData(checkedKeys)
        
        if (importData.length === 0) {
          this.$message.warning('请选择要导入的公司')
          return
        }
        
        this.importLoading = true
        importThirdTree(importData).then(res => {
          if (res.code == 200) {
            this.$message({
              message: '导入成功',
              type: 'success'
            })
            this.importDialogVisible = false
            this.getList()
          }
          this.importLoading = false
        }).catch(() => {
          this.importLoading = false
        })
      },
      // 构建导入数据结构
      buildImportData(checkedKeys) {
        // 从原始数据中查找所有选中的节点
        const findNodeById = (nodes, id) => {
          for (const node of nodes) {
            if (node.Id === id) {
              return node
            }
            if (node.Children && node.Children.length > 0) {
              const found = findNodeById(node.Children, id)
              if (found) return found
            }
          }
          return null
        }
        
        // 递归构建树形结构，只包含选中的节点及其选中的子节点
        const buildTree = (node) => {
          const result = {
            Id: node.Id,
            T_mid: node.T_mid,
            T_name: node.T_name,
            T_key: node.T_key || '',
            T_Address: node.T_Address || node.companyAddress || ''
          }
          
          // 处理子节点
          if (node.Children && node.Children.length > 0) {
            const selectedChildren = node.Children
              .filter(child => checkedKeys.includes(child.Id))
              .map(child => buildTree(child))
            
            if (selectedChildren.length > 0) {
              result.Children = selectedChildren
            }
          }
          
          return result
        }
        
        // 找出所有根节点（T_mid为0或父节点未被选中）
        const rootNodes = []
        for (const id of checkedKeys) {
          const node = findNodeById(this.thirdTreeData, id)
          if (node) {
            // 检查是否是根节点
            const isRoot = node.T_mid === 0 || !checkedKeys.includes(node.T_mid)
            if (isRoot) {
              rootNodes.push(node)
            }
          }
        }
        
        // 构建树形结构
        return rootNodes.map(node => buildTree(node))
      },
      // 关闭导入对话框
      closeImportDialog() {
        this.thirdTreeData = []
        this.selectedCompanyNodes = []
        if (this.$refs.companyTree) {
          this.$refs.companyTree.setCheckedKeys([])
        }
      },
      // 删除公司
      deleteUser(id) {
        this.$confirm('此操作将永久删除该公司, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          delCompany({
            id: id,
          }).then(res => {
            if (res.code == 200) {
              this.$message({
                message: '操作成功',
                type: 'success'
              });
              this.getList()
            }
          })
        }).catch(() => {});
      },
      changeSize(val) {
        this.Pagination.PageSize = val
        this.getList()
      },
      changeCurrent(val) {
        this.Pagination.PageIndex = val
        this.getList()
      },
      // 清空表单
      closeDialog() {
        // this.ruleForm = {}
        this.ruleForm.name = ''
        this.ruleForm.appName = ''
        this.ruleForm.companyAddress = ''
        this.ruleForm.coldKey = ''
        this.ruleForm.isIceReleaseCold = false
        this.ruleForm.isCoolerReleaseCold = false
        this.ruleForm.isOutStorage = false
        this.ruleForm.iceRaftManage = false
        this.ruleForm.remark = ''
        this.$refs.childRules.resetCheck();
      }
    }
  }
</script>
