<template>
  <div style="margin-top: -10px;">
    <el-form ref="queryFormRef" :model="queryParams" :inline="true" @keyup.enter.native="queryList">
      <el-form-item label="用户姓名:">
        <el-input v-model="queryParams.userName" placeholder="用户姓名" width="120px" size="small" />
      </el-form-item>
      <el-form-item label="手机号码:">
        <el-input v-model="queryParams.loginId" placeholder="手机号码" width="120px" size="small" />
      </el-form-item>

      <el-form-item label="用户类型:">
        <el-select v-model="queryParams.userType" placeholder="用户类型" size="small" clearable>
          <el-option v-for="(key, value) in userTypeMap" :key="key" :label="key" :value="value" />
        </el-select>
      </el-form-item>

      <el-form-item label="所属单位:">
        <el-select v-model="queryParams.unitCode" style="width: 250px;" size="small" filterable clearable
          placeholder="所属单位">
          <el-option v-for="item in state.unitData" :key="item.unitCode" :label="item.unitName" :value="item.unitCode">
          </el-option>
        </el-select>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" class="button" @click="queryList">查询用户</el-button>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" class="button" @click="handleAdd" :disabled="!adminFlag">新增用户</el-button>
      </el-form-item>
    </el-form>
    <!-- <div class="wrapper"> -->
    <el-table v-loading="loading" :data="state.tableData" border stripe style="width: 100%;margin-top: -20px;"
      :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="userName" label="用户姓名" header-align="center" width="120" align="center" />
      <el-table-column prop="loginId" label="手机号码" header-align="center" width="110" />
      <el-table-column label="管理员" header-align="center" align="center" width="80">
        <template #default="scope">
          <span v-if="scope.row.highAuthFlag === '0'" style="color:red;">✖</span>
          <span v-if="scope.row.highAuthFlag === '1'" style="color:green;">✔</span>
        </template>
      </el-table-column>
      <el-table-column label="当前状态" header-align="center" align="center" width="90">
        <template #default="scope">
          <el-tag :type="mapColorMap[scope.row.useFlag]">{{ UseStateMap[scope.row.useFlag] }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="dicConfigAuthModel.authName" label="配置角色" header-align="center" width="90"
        align="center" />
      <el-table-column label="用户类型" header-align="center" align="center" width="80">
        <template #default="scope">
          <span>{{ userTypeMap[scope.row.userType] }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="unitName" label="所属单位" header-align="center" width="200" align="left" />
      <el-table-column prop="createMan" label="创建人" header-align="center" width="100" align="center" />
      <el-table-column prop="createTime" label="创建时间" header-align="center" width="155" />
      <el-table-column label="" align="left" width="95">
        <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-column fixed="right"></el-table-column>
    </el-table>
    <!-- </div> -->
    <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.small" :disabled="state.disabled"
        :background="state.background" layout="total, sizes, prev, pager, next, jumper" :total="state.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="450px" draggable center>
      <el-form ref="dataFormRef" :model="formData" label-width="100px" :rules="state.rules">
        <el-form-item label="用户姓名:" prop="userName">
          <el-input v-model="formData.userName" placeholder="用户姓名" width="120px" minlength="2" maxlength="10" />
        </el-form-item>
        <el-form-item label="手机号码:" prop="loginId">
          <el-input v-model="formData.loginId" placeholder="手机号码" width="120px" minlength="11" maxlength="11"
            type='number' />
        </el-form-item>
        <el-form-item label="登录密码:" prop="loginPwd">
          <el-input v-model="formData.loginPwd" placeholder="登录密码" width="120px" show-password maxlength="20" />
        </el-form-item>

        <el-form-item label="配置角色:">
          <el-select v-model="formData.configAuthId" placeholder="选择APP配角色" size="large" style="width: 300px;">
            <el-option v-for="item in configAuthList" :key="item.authId" :label="item.authName" :value="item.authId" />
          </el-select>
        </el-form-item>
        <el-form-item label="用户类型:" prop="userType">
          <el-select v-model="formData.userType" placeholder="用户类型" size="large" style="width: 300px;">
            <el-option v-for="(key, value) in userTypeMap" :key="key" :label="key" :value="value" />
          </el-select>
        </el-form-item>
        <el-form-item label="管理员:">
          <el-switch v-model="formData.highAuthFlag" inline-prompt="true" active-value="1" inactive-value="0" />
        </el-form-item>
        <el-form-item label="在用状态:">
          <el-switch v-model="formData.useFlag" inline-prompt="true" active-value="1" inactive-value="0" />
        </el-form-item>
        <el-form-item label="所属单位:" v-if="formData.userType && formData.userType === '1'">
          <el-select v-model="formData.unitCode" style="width: 250px;" filterable clearable placeholder="选择站点的归属单位">
            <el-option v-for="item in state.unitData" :key="item.unitCode" :label="item.unitName"
              :value="item.unitCode"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>

        </el-form-item>
      </el-form>
      <div style="text-align: center;">
        <el-button @click="cancel()">取消</el-button>
        <el-button type="primary" @click="submitForm">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { reactive, toRefs, toRef, ref, onMounted } from "vue";
import { ElForm, ElMessage, ElMessageBox } from 'element-plus';
import AppUserAction from "@/api/app/appuser";
import DicConfigauthAction from "@/api/app/dicconfigauth";
import { AppUserQueryParam, AppUserModel, DicConfigAuthQueryParam, DicConfigAuthModel, Dialog, PageResult, TAffiliatedunitModel, TAffiliatedunitQueryParam } from '@/types';
import TAffAction from "@/api/customermanagement/taffiliatedunit";
import zhCn from 'element-plus/lib/locale/lang/zh-cn';
import { stat } from "fs";
import tool from "@/until/tool";

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

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

const userTypeMap: mapStatee = {
  0: '内部',
  1: '客户',
};

const mapColorMap: mapStatee = {
  1: 'success',
  0: 'danger',
};

const loading = ref(false)

const state = reactive({
  currentType: 0,
  queryParams: { page: 1, rows: 10 } as AppUserQueryParam,
  queryAuthParams: { page: 1, rows: 10 } as DicConfigAuthQueryParam,
  total: 0,
  small: false,
  background: false,
  disabled: false,
  dialog: {} as Dialog,
  formData: {} as AppUserModel,
  UseStateMap,
  tableData: [] as AppUserModel[],
  configAuthList: [] as DicConfigAuthModel[],
  rules: {
    userName: [
      { required: true, message: "用户姓名不能为空", trigger: "blur" },
      { min: 2, max: 15, message: "用户姓名长度不合法", trigger: "blur" },
    ],
    loginId: [
      { required: true, message: "手机号码不能为空", trigger: "blur" },
      { min: 11, max: 11, message: "手机号码长度不合法", trigger: "blur" },
    ],
    loginPwd: [
      { required: true, message: "登陆密码不能为空", trigger: "blur" },
      { min: 3, max: 20, message: "登陆密码长度不合法", trigger: "blur" },
    ],
    userType: [
      { required: true, message: "用户类型不能为空", trigger: "blur" }
    ],
  },
  unitData: [] as TAffiliatedunitModel[],
});

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

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

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

async function handleAdd() {
  //queryAuthList();
  state.currentType = 0;
  state.formData = {} as AppUserModel;
  state.formData.useFlag = '1';
  state.dialog = {
    title: '新增用户',
    visible: true,
    disabled: false,
  };
}

async function handleEdit(row: any) {
  //queryAuthList();
  state.currentType = 1;
  state.formData = 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;
  AppUserAction.QueryAppUserList(queryParams.value).then(result => {
    if (result.status === 200) {
      const { res, flag, error } = result.data;
      if (flag === "1") {
        const pageData = res as PageResult<AppUserModel[]>;
        state.tableData = pageData.list;
        state.total = pageData.total;
      } else {
        ElMessage.error(error);
      }
    }
  }).catch(error => {
    //请求失败时的操作
  })
  loading.value = false;
};

const submitForm = () => {
  dataFormRef.value.validate((valid: any) => {
    if (valid) {
      if (state.formData.userType === '1' && tool.stringIsNullOrEmpty(state.formData.unitCode)) {
        ElMessage.warning('所属单位不能为空');
        return;
      }
      if (state.currentType == 0) {
        state.formData.createMan = localStorage.getItem("UserName") || "";
        AppUserAction.AddAppUser(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);
            }
          }
        });
      }
      else {
        AppUserAction.EditAppUser(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);
            }
          }
        });
      }
    }
  });
};

const submitDeleteForm = (row: any) => {
  ElMessageBox.confirm(
    ' 是否删除用户[' + row.userName + ']? ',
    '提示',
    {
      cancelButtonText: '取消',
      confirmButtonText: '确认',
      type: 'warning',
      center: true,
    }
  )
    .then(() => {
      AppUserAction.DeleteAppUser(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 = () => {
  dataFormRef.value.resetFields();
  state.formData = {} as AppUserModel;
  state.dialog.visible = false;
}

const queryAuthList = () => {
  DicConfigauthAction.QueryDicConfigAuthList(state.queryAuthParams).then(result => {
    if (result.status === 200) {
      const { res, flag, error } = result.data;
      if (flag != undefined && flag == 1) {
        const pageData = res as PageResult<DicConfigAuthModel[]>;
        state.configAuthList = pageData.list;
      } else {
        ElMessage.error(error);
      }
    }
  }).catch(error => {
    //请求失败时的操作     
  })
};

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

const dialogClose = () => {
  cancel();
}

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

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