<template>
  <div>
    <div>
      <el-row :gutter="20">
        <el-col :span="9">
          <el-card>
            <template #header>
              <div class="card-header">
                <span style="font-size:20px;">请选择需要授权的单位</span>
              </div>
            </template>
            <div>
              <el-table v-loading="loading" :data="state.tableData" border stripe :height="tableHeight" ref="table"
                highlight-current-row @current-change="handleCurrentRowChange" :show-header="false">
                <!-- <el-table-column fixed type="selection" width="50" align="center" />     @selection-change="handleSelectionChange"-->
                <el-table-column fixed prop="unitName" label="单位名称" />
              </el-table>
            </div>
          </el-card>
        </el-col>
        <el-col :span="15">
          <el-card>
            <template #header>
              <div class="card-header">
                <span style="font-size:20px;">请选择该单位可查看的站点</span>
                <el-button type="primary" style="margin-left: 10px;float: right;" @click="saveStationCfg"
                  :disabled="adminFlag">保存授权
                </el-button>
              </div>
            </template>
            <div>
              <el-tree class="tree" :data="state.groupData" :property="defaultProps" ref="tree" node-key="id"
                :expand-on-click-node="false" show-checkbox>
                <template #default="{ node, data }">
                  <el-icon v-if="data.type === '0' || data.type === '1'" :size="15" color="#409EFC">
                    <Folder />
                  </el-icon>
                  <el-icon v-else :size="20">
                    <Odometer />
                  </el-icon>
                  <span :title="node.label" class="custom-tree-node"> {{ node.label }}</span>
                </template>
              </el-tree>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { reactive, toRefs, ref, onMounted } from "vue";
import { ElForm, ElMessage, ElMessageBox, ElTable, ElTree } from 'element-plus';
import TAffAction from "@/api/customermanagement/taffiliatedunit";
import StationAccAction from "@/api/station/stationacc";
import { TUsingunitGroupQueryParam, TUsingunitGroupModel, TAffiliatedunitQueryParam, TAffiliatedunitModel, GroupAndStationTree, Dialog, PageResult, StationAccUpdataModel } from '@/types';
import zhCn from 'element-plus/lib/locale/lang/zh-cn';
import arrayToTree from "array-to-tree";

let locale = ref(zhCn)

const dataFormRef = ref(ElForm); // 属性名必须和元素的ref属性值一致
const adminFlag = localStorage.getItem("AdminFlag")?.toString() !== '1';

const tree = ref(ElTree);
const table = ref(ElTable);

interface Option {
  key: string
  label: string
  disabled: boolean
}

const defaultProps = {
  children: "children", //"children"内的每个对象解析为一个子项;
  label: "label", //所有"label"所在的对象解析为一个父项
};

type mapStatee = Record<string, string>;
const UseStateMap: mapStatee = {
  0: '停用',
  1: '使用中',
};

const loading = ref(false)

const state = reactive({
  currentType: 0,
  queryParams: { unitName: '', page: 1, rows: 10 } as TUsingunitGroupQueryParam,
  pagination: {
    total: 0,
    small: false,
    background: false,
    disabled: false,
  },
  UseStateMap,
  tableData: [] as TAffiliatedunitModel[],
  groupData: [] as GroupAndStationTree[],
  rules: {
    authNumber: [
      { required: true, message: "授权数量不能为空", trigger: "blur" }
    ],
  },
});

const {
  queryParams,
  tableData,
  groupData
} = toRefs(state);

const tableHeight = ref(document.documentElement.clientHeight - 200);
const currentRow = ref()

const handleCurrentRowChange = (val: TUsingunitGroupModel | undefined) => {
  currentRow.value = val;

  tree.value!.setCheckedKeys([], false);
  if (val !== undefined) {
    getUnitTree(val.unitCode);
  }
}

onMounted(() => {
  window.onresize = function () {
    tableHeight.value = document.documentElement.clientHeight - 200
  }

  queryTreeList();
  queryUnit();
})

const queryUnit = () => {
  let queryModel = {} as TAffiliatedunitQueryParam;

  TAffAction.QueryTAffiliatedunitList(queryModel).then(result => {
    if (result.status === 200) {
      const { res, flag, error } = result.data;
      if (flag === "1") {
        const pageData = res as PageResult<TAffiliatedunitModel[]>;
        state.tableData = pageData.list.filter(s => s.unitType !== '4');    //不显示使用单位
      } else {
        ElMessage.error(error);
      }
    }
    loading.value = false;
  }).catch(error => {
    //请求失败时的操作     
    ElMessage.error(error);
    loading.value = false;
  })
}

const queryTreeList = () => {
  StationAccAction.QueryAllStationTree()
    .then((result) => {
      if (result.status === 200) {
        const { res, flag, error } = result.data;
        if (flag === "1") {
          if (res !== null) {
            let treeArray = res as GroupAndStationTree[];
            let treeArrayNew = [] as GroupAndStationTree[];
            treeArray.forEach(eleme => {
              treeArrayNew.push(eleme);
            });

            state.groupData = arrayToTree(treeArrayNew, {
              parentProperty: "parentcode",
              customID: "code",
              childrenProperty: "children",
            });
          }
        } else {
          ElMessage.error(error || "未知异常...")
        }
      }
    })
    .catch((error) => {
      //请求失败时的操作
      ElMessage.error(error || "未知异常...")
    });
};

//保存配置信息
const saveStationCfg = () => {
  if (currentRow.value === undefined) return;
  let selKeys = tree.value.getCheckedKeys() as string[];
  let unitModel = currentRow.value as TAffiliatedunitModel;
  let model = {} as StationAccUpdataModel;
  model.visUnitCode = unitModel.unitCode;
  model.stationCodes = selKeys;

  StationAccAction.UpdateVisUnitCodes(model).then((result) => {
    if (result.status === 200) {
      const { res, flag, error } = result.data;
      if (flag === "1") {
        //保存成功,取消所有选中
        ElMessage.success("保存成功");
        // tree.value!.setCheckedKeys([], false);
        // table.value!.clearSelection();
      } else {
        ElMessage.error(error || "未知异常...")
      }
    }
  })
    .catch((error) => {
      //请求失败时的操作
      ElMessage.error(error || "未知异常...")
    });
};

//根据选中的站代码获取树
const getUnitTree = (unitCode: string) => {
  StationAccAction.QueryStationTreeByUnitCode(unitCode).then((result) => {
    if (result.status === 200) {
      const { res, flag, error } = result.data;
      
      if (flag === "1") {
        if (res !== null) {
          let treeArray = res as GroupAndStationTree[];
          treeArray=treeArray.filter(s=>s.type==='2')
          tree.value!.setCheckedNodes(treeArray);
        }
      } else {
        ElMessage.error(error || "未知异常...")
      }
    }
  })
    .catch((error) => {
      //请求失败时的操作
      ElMessage.error(error || "未知异常...")
    });
}
</script>

<style lang="scss" scoped>
.button {
  margin: 10px 0;
}

.tree {
  overflow-y: scroll;
  overflow-x: scroll;
  width: 100%;
  height: calc(100vh - 200px);
  overflow: auto;
}

::v-deep .el-transfer-panel {
  width: 400px;
  height: 750px;
}

::v-deep .el-table__body tr.current-row>td {
  color: #fff;
  background: #6db3fa !important;
}
</style>