<template>
  <div>
    <div>
      <el-row :gutter="20">
        <el-col :span="9">
          <div>
            <el-table v-loading="loading" :data="state.tableData" border stripe :height="tableHeight"
              highlight-current-row @current-change="handleCurrentRowChange"
              :header-cell-style="{ background: '#606266', color: '#FFFFFF' }">
              <el-table-column fixed type="index" width="50" align="center" />
              <el-table-column fixed prop="groupName" label="分组名称" />
              <el-table-column label="" align="left" width="180">
                <template #default="scope">
                  <el-button type="text" @click="handleEdit(scope.row)" :disabled="adminFlag">编辑</el-button>
                  <el-button type="text" @click="submitDeleteForm(scope.row)" :disabled="adminFlag">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
            <el-form>
              <el-form-item>
                <el-button type="primary" class="button" @click="handleAdd" style="margin-left: 10px" :disabled="adminFlag">新增分组</el-button>
              </el-form-item>
            </el-form>
          </div>
        </el-col>
        <el-col :span="15">
          <div >
            <el-transfer class="transfer-high" :data="state.transferLeft" v-model="state.transferRight" :titles="['可选站点', '已选站点']"/>
            <el-button type="primary" @click="saveStationInfo" style="margin-right: 20px;margin-top: 10px;float: right;" :disabled="adminFlag">
              保存站点变更</el-button>
          </div>
        </el-col>
      </el-row>
    </div>

    <el-dialog :title="dialog.title" v-model="dialog.visible" width="480px" draggable center>
      <el-form ref="dataFormRef" :model="formData" label-width="100px" :rules="state.rules">
        <el-form-item label="分组名称:" prop="groupName">
          <el-input v-model="formData.groupName" placeholder="分组名称" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="cancel()">取消</el-button>
          <el-button type="primary" @click="submitForm" :disabled="dialog.disabled">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

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

let locale = ref(zhCn)

const change = () => {
  console.log(state.transferRight);
};

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

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

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

const loading = ref(false)
const userType = ref(localStorage.getItem("UserType"))
const state = reactive({
  currentType: 0,
  queryParams: { unitName: '', page: 1, rows: 10 } as TUsingunitGroupQueryParam,
  pagination: {
    total: 0,
    small: false,
    background: false,
    disabled: false,
  },
  dialog: { disabled: false } as Dialog,
  formData: {} as TUsingunitGroupModel,
  UseStateMap,
  tableData: [] as TUsingunitGroupModel[],
  unitData: [] as TAffiliatedunitModel[],
  transferLeft: [] as Option[],
  transferRight: [] as string[],
  selectRow: {} as TUsingunitGroupModel,
  rules: {
    groupName: [
      { required: true, message: "分组名称不能为空", trigger: "blur" }
    ],
  },
});

const {
  queryParams,
  dialog,
  formData,
  tableData,
  unitData
} = toRefs(state);

const tableHeight = ref(800);
const currentRow = ref()

const handleCurrentRowChange = (val: TUsingunitGroupModel | undefined) => {
  currentRow.value = val;
  if (val != undefined) {
    let row = val as TUsingunitGroupModel;
    queryTreeList(row);
    state.selectRow = row;
  }
}

const handleAdd = () => {
  state.currentType = 0;
  state.formData = {} as TUsingunitGroupModel;
  state.formData.useFlag = "1";
  state.dialog = {
    title: '新增分组',
    visible: true,
    disabled: false,
  };
}

const saveStationInfo = () => {
  if(state.selectRow===null||tool.stringIsNullOrEmpty(state.selectRow.groupCode)){
    ElMessage.warning("请选择分组");
    return;
  }
  state.selectRow.stationCodes=state.transferRight.join(",");
  TUsingunitGroupAction.EditTUsingunitGroup(state.selectRow).then(result => {
    if (result.status === 200) {
      const { res, flag, error } = result.data;
      if (flag === "1") {
        ElMessage.success('保存成功');
        cancel();
        queryList();
      } else {
        ElMessage.error(error);
      }
    }
    state.dialog.disabled = false;
  });
}

const handleEdit = (row: TUsingunitGroupModel) => {
  state.currentType = 1;
  state.formData = JSON.parse(JSON.stringify(row));;
  state.dialog = {
    title: '编辑分组',
    visible: true,
    disabled: false,
  };
}

const handleSizeChange = (val: number) => {
  queryParams.value.rows = val;
  queryList();
};

const handleCurrentChange = (val: number) => {
  queryParams.value.page = val;
  queryList();
};

const queryList = () => {
  loading.value = true;
  if (userType.value === '1') {
    let unitCode = localStorage.getItem("UnitCode");
    state.queryParams.unitCode = unitCode?.toString();
  }

  TUsingunitGroupAction.QueryTUsingunitGroupList(queryParams.value).then(result => {
    if (result.status === 200) {
      const { res, flag, error } = result.data;
      if (flag === "1") {
        state.tableData = res as TUsingunitGroupModel[];
      } else {
        ElMessage.error(error);
      }
    }
    loading.value = false;
  }).catch(error => {
    //请求失败时的操作     
    ElMessage.error(error);
    loading.value = false;
  })
};

const submitForm = () => {
  dataFormRef.value.validate((valid: any) => {
    if (valid) {
      state.dialog.disabled = true;
      if (state.currentType === 0) {
        let unitCode = localStorage.getItem("UnitCode") as string;

        state.formData.unitCode = unitCode;
        state.formData.useFlag = '1';
        state.formData.createMan == localStorage.getItem("UserName") || "";
        TUsingunitGroupAction.AddTUsingunitGroup(state.formData).then(result => {
          if (result.status === 200) {
            const { res, flag, error } = result.data;
            if (flag === "1") {
              ElMessage.success('新增成功');
              cancel();
              queryList();
            } else {
              ElMessage.error(error);
            }
          }
          state.dialog.disabled = false;
        });
      }
      else if (state.currentType === 1)
        TUsingunitGroupAction.EditTUsingunitGroup(state.formData).then(result => {
          if (result.status === 200) {
            const { res, flag, error } = result.data;
            if (flag === "1") {
              ElMessage.success('编辑成功');
              cancel();
              queryList();
            } else {
              ElMessage.error(error);
            }
          }
          state.dialog.disabled = false;
        });
    }
  });


};

const submitDeleteForm = (row: any) => {
  ElMessageBox.confirm(
    ' 是否删除[' + row.groupName + ']的分组? ',
    '提示',
    {
      cancelButtonText: '取消',
      confirmButtonText: '确认',
      type: 'warning',
      center: true,
    }
  ).then(() => {
    TUsingunitGroupAction.DeleteTUsingunitGroup(row.id).then(result => {
      if (result.status === 200) {
        const { res, flag, error } = result.data;
        if (flag === "1") {
          ElMessage.success('删除成功');
          queryList();
        } else {
          ElMessage.error(error);
        }
      }
    });
  })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '取消删除成功!',
      })
    })
};

const cancel = () => {
  state.formData = {} as TUsingunitGroupModel;
  state.dialog.visible = false;
}

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

  queryList();
})

const queryTreeList = (row: TUsingunitGroupModel) => {
  StationAccAction.QueryStationTreeByUnitCode(row.unitCode)
    .then((result) => {
      if (result.status === 200) {
        const { res, flag, error } = result.data;
        if (flag === "1") {
          let treeArray = res as GroupAndStationTree[];

          const left: Option[] = [];
          const right: string[] = [];
          treeArray.forEach(eleme => {
            if (eleme.type === '2' && eleme.parentcode === row.groupCode) {
              //当前已经在选中分组内的
              left.push({
                key: eleme.code,
                label: eleme.label,
                disabled: false
              });
              right.push(eleme.code);
            } else if (eleme.type === '2' && eleme.parentcode === row.unitCode) {
              //用户未分组的设备
              left.push({
                key: eleme.code,
                label: eleme.label,
                disabled: false
              })
            }
          });
          state.transferLeft = left;
          state.transferRight = right;
        } else {
          ElMessage.error(error || "未知异常...")
        }
      }
    })
    .catch((error) => {
      //请求失败时的操作
      ElMessage.error(error || "未知异常...")
    });
};


const queryUnit = () => {
  let userType = localStorage.getItem("UserType");

  let queryModel = {} as TAffiliatedunitQueryParam;
  queryModel.unitType = '4';
  if (userType === '1') {
    let unitCode = localStorage.getItem("UnitCode");
    queryModel.unitCode = unitCode as string;
  }

  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.unitData = pageData.list;
      } else {
        ElMessage.error(error);
      }
    }
    loading.value = false;
  }).catch(error => {
    //请求失败时的操作     
    ElMessage.error(error);
    loading.value = false;
  })
}
</script>

<style lang="scss" scoped>
.button {
  margin: 10px 0;
}
::v-deep .el-transfer-panel {
  width: 420px;
  height: calc(100vh - 140px);
}
</style>