<template>
  <div>
    <el-form ref="queryFormRef" :model="queryParams" :inline="true" v-if="adminFlag" style="height: 65px;" @keyup.enter.native="queryList">
      <el-form-item label="用户姓名">
        <el-input v-model="queryParams.userName" placeholder="客户名称" width="120px" clearable/>
      </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">新增用户</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="userName" label="用户名称" header-align="center" width="120" />
      <el-table-column prop="loginId" label="登录ID" header-align="center" width="120" />
      <el-table-column prop="customMobile" label="联系方式" header-align="center" width="120" />
      <el-table-column prop="unitName" label="所属单位" header-align="center" min-width="120" />
      <el-table-column prop="unitType" label="用户类型" header-align="center" width="80">
        <template #default="scope">
          <span v-if="scope.row.unitType === '0'">用户</span>
          <span v-if="scope.row.unitType === '1'">子用户</span>
        </template>
      </el-table-column>
      <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 label="在用状态" header-align="center" align="center" width="100">
        <template #default="scope">
          <el-tag :type="mapColorMap[scope.row.useFlag]">{{ UseStateMap[scope.row.useFlag] }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="创建方式" header-align="center" align="center" width="100">
        <template #default="scope">
          <span v-if="scope.row.rgeAuthCode !== ''">自主注册</span>
          <span v-if="scope.row.rgeAuthCode == ''">管理创建</span>
        </template>
      </el-table-column>
      <el-table-column prop="createMan" label="创建人" header-align="center" width="120" />
      <el-table-column prop="createTime" label="创建时间" header-align="center" width="160" />
      <el-table-column label="" align="left" width="100">
        <template #default="scope">
          <el-button type="text" @click="handleEdit(scope.row)" :disabled="!adminFlag&&userId!==scope.row.userId">编辑</el-button>
          <el-button type="text" @click="submitDeleteForm(scope.row)" :disabled="!adminFlag">删除</el-button>
        </template>
      </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">
        <el-form-item label="用户名称:">
          <el-input v-model="formData.userName" placeholder="用户名称" width="120px" />
        </el-form-item>
        <el-form-item label="登陆ID:">
          <el-input v-model="formData.loginId" placeholder="登录ID" width="120px" />
        </el-form-item>
        <el-form-item label="登录密码:">
          <el-input v-model="formData.loginPwd" placeholder="登录密码" width="120px" show-password />
        </el-form-item>
        <el-form-item label="联系方式:">
          <el-input v-model="formData.customMobile" placeholder="用户手机" width="120px" />
        </el-form-item>
        <el-form-item label="在用状态:" v-if="adminFlag">
          <el-switch v-model="formData.useFlag" inline-prompt="true" active-value="1" inactive-value="0" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="cancel()">取消</el-button>
          <el-button type="primary" @click="submitForm" :disabled="state.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 CusTomUserAction from "@/api/customermanagement/customuser";
import { CustomUserQueryParam, CustomUserModel, Dialog, PageResult } from '@/types';
import tool from "@/until/tool"
import zhCn from 'element-plus/lib/locale/lang/zh-cn';
import { Color } from "csstype";

let locale = ref(zhCn)

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

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

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

const loading = ref(false)

const state = reactive({
  currentType: 0,
  queryParams: { page: 1, rows: 10 } as CustomUserQueryParam,
  total: 0,
  small: false,
  background: false,
  disabled: false,
  dialog: {} as Dialog,
  formData: {} as CustomUserModel,
  dialog_disabled: false,
  UseStateMap,
  tableData: [] as CustomUserModel[]
});

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

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

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

const handleAdd = () => {
  state.currentType = 0;
  state.formData = {} as CustomUserModel;
  state.dialog = {
    title: '新增客户',
    visible: true,
    disabled: false,
  };
}

const handleEdit = (row: CustomUserModel) => {
  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;
  state.queryParams.userId = userId;
  if (userType === '0') {
    state.queryParams.adminFlag = '1';  //内部用户跳过后台验证UserID
  }else{
    state.queryParams.unitCode=localStorage.getItem("UnitCode") + '';
  }
  CusTomUserAction.QueryCustomUserList(queryParams.value).then(result => {
    if (result.status === 200) {
      const { res, flag, error } = result.data;
      if (flag === "1") {
        const pageData = res as PageResult<CustomUserModel[]>;
        state.tableData = pageData.list;
        state.total = pageData.total;
      } else {
        ElMessage.error(error);
      }
    }
    loading.value = false;
  }).catch(error => {
    //请求失败时的操作     
    ElMessage.error(error);
    loading.value = false;
  })
};

const submitForm = () => {
  state.dialog_disabled = true;
  if (state.currentType == 0) {
    state.formData.createMan = localStorage.getItem("UserName") || "";
    CusTomUserAction.AddCustomUser(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 {
    CusTomUserAction.EditCustomUser(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.userName + ']? ',
    '提示',
    {
      cancelButtonText: '取消',
      confirmButtonText: '确认',
      type: 'warning',
      center: true,
    }
  )
    .then(() => {
      CusTomUserAction.DeleteCustomUser(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 CustomUserModel;
  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>