<template>
  <div>
    <el-form ref="queryFormRef" :model="queryParams" :inline="true" style="height: 65px;" @keyup.enter.native="queryList">
      <el-form-item label="单位名称">
        <el-input v-model="queryParams.unitName" placeholder="单位名称" width="120px" clearable/>
      </el-form-item>
      <!-- <el-form-item label="可用状态">
        <el-select v-model="queryParams.authUseNum" class="filter-item" size="small" style="max-width: 150px;">
          <el-option v-for="(key, value) in authStatusMap" :key="key" :label="key" :value="value" />
        </el-select>
      </el-form-item> -->
      <el-form-item>
        <el-button type="primary" class="button" @click="queryList">查询授权</el-button>
      </el-form-item>
    </el-form>
    <el-table v-loading="loading" :data="state.tableData" border stripe style="width: 100%" :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="unitName" label="单位名称" header-align="center" width="260"
        show-overflow-tooltip="unitName" />
      <el-table-column fixed prop="authCode" label="授权码" header-align="center" width="320" />
       <el-table-column label="管理员" header-align="center" align="center" width="80">
        <template #default="scope">
          <span v-if="scope.row.adminFlag !== '1'" style="color:red;">✖</span>
          <span v-if="scope.row.adminFlag === '1'" style="color:green;">✔</span>
        </template>
      </el-table-column>
      <el-table-column prop="authNumber" label="授权数量" header-align="center" width="80" />
      <el-table-column prop="authUseNum" label="已用数量" header-align="center" width="80" />
      <el-table-column prop="createMan" label="创建人" header-align="center" width="120" />
      <el-table-column prop="createUnitName" label="创建单位" header-align="center" min-width="90" />
      <el-table-column label="创建时间" header-align="center" width="130">
        <template #default="scope">
          {{ tool.dateFormat(scope.row.createTime, "YYYY-MM-DD HH:mm:ss") }}
        </template>
      </el-table-column>
      <el-table-column prop="memo" label="备注" header-align="center" width="150" />
      <el-table-column label="" align="left" width="100">
        <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-config-provider :locale="locale">
      <el-pagination v-model:currentPage="queryParams.page" v-model:page-size="queryParams.rows"
        :page-sizes="[10, 15, 20, 25, 100]" :small="state.pagination.small" :disabled="state.pagination.disabled"
        :background="state.pagination.background" layout="total, sizes, prev, pager, next, jumper"
        :total="state.pagination.total" style="text-align: center;margin-top: 10px;" @size-change="handleSizeChange"
        @current-change="handleCurrentChange" />
    </el-config-provider>

    <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="单位名称:">
          <el-input v-model="formData.unitName" placeholder="单位名称" disabled />
        </el-form-item>
        <el-form-item label="授权数量:" prop="authNumber">
          <el-input v-model="formData.authNumber" placeholder="授权数量" type="number" maxlength="2" />
        </el-form-item>
        <el-form-item label="备注信息:">
          <el-input v-model="formData.memo" placeholder="备注信息" />
        </el-form-item>
        <el-form-item label="授权码:">
          <el-input v-model="formData.authCode" disabled />
        </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 TRgeAuthAction from "@/api/customermanagement/trgeauth";
import { TRgeAuthQueryParam, TRgeAuthModel, Dialog, PageResult } from '@/types';
import tool from "@/until/tool"
import zhCn from 'element-plus/lib/locale/lang/zh-cn';

let locale = ref(zhCn)

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

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

const authStatusMap: mapStatee = {
  0: '全部',
  1: '可用',
  2: '上限',
};

const loading = ref(false)

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

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

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

const handleCurrentRowChange = (val: TRgeAuthModel | undefined) => {
  currentRow.value = val
}

const handleEdit = (row: TRgeAuthModel) => {
  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;
  TRgeAuthAction.QueryTRgeAuthList(queryParams.value).then(result => {
    if (result.status === 200) {
      const { res, flag, error } = result.data;
      if (flag === "1") {
        const pageData = res as PageResult<TRgeAuthModel[]>;
        state.tableData = pageData.list;
        state.pagination.total = pageData.total;
      } 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.formData.authNumber<=0){
        ElMessage.warning('授权数量不合法');
        return;
      }
      TRgeAuthAction.EditTRgeAuth(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.unitName + ']的授权码? ',
    '提示',
    {
      cancelButtonText: '取消',
      confirmButtonText: '确认',
      type: 'warning',
      center: true,
    }
  ).then(() => {
    TRgeAuthAction.DeleteTRgeAuth(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 TRgeAuthModel;
  state.dialog.visible = false;
}

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

  queryList();
})
</script>

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