<!--客户管理-->
<template>
  <div class="vue-element-page-wrap" ref="tableContainer">
    <el-row class="page-search" justify="space-between" align="middle">
      <el-form ref="queryFormRef" :model="queryParams" :inline="true">
        <el-row :gutter="20">
          <el-col :span="6">
            <el-form-item label="客户编号" prop="params.account">
              <el-Input v-model="queryParams.params.CUSTOMERNO" placeholder="客户编号" clearable
                @keyUpEvent="queryInfo" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="客户名称" prop="params.account">
              <el-Input v-model="queryParams.params.CUSTOMERNAME" placeholder="客户名称" clearable
                @keyUpEvent="queryInfo" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="客户简称" prop="params.account">
              <el-Input v-model="queryParams.params.CUSTNO" placeholder="客户简称" clearable @keyUpEvent="queryInfo" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div class="page-search-btns">
        <el-button type="primary" @click="queryInfo" :disabled="state.disableds" v-loadig="state.loadings">搜索</el-button>
        <el-button @click="resetQuery">重置</el-button>
      </div>
    </el-row>

    <div class="vue-element-page-table">
      <div class="page-table-operate">
        <div class="page-table-title">
          <div class="page-table-title-left">
            <span>客户信息列表</span>
          </div>
        </div>
        <div class="page-table-operateBtns">
          <el-button type="primary" @click="handleAdd">
            <el-icon>
              <Plus />
            </el-icon>
            创建
          </el-button>
          <el-popover :persistent="false" placement="right" popper-class="config-table-wrap" trigger="click">
            <template #reference>
              <el-button class="operateBtns-setting">
                <svg-icon icon-class="table_title" width="16px" height="16px" />
              </el-button>
            </template>
            <ConfigTable :list="column" @updateList="updateList" />
          </el-popover>
        </div>
      </div>
      <el-table :height="tableHeight" border v-loading="loading" :data="state.customerList" highlight-current-row row-key="id"
        style="width: 100%">
        <template v-for="(col, index) in column" :key="index">
          <el-table-column v-if="!col.hide" :label="col.header" show-overflow-tooltip>
            <template #default="scope">
              <span v-if="col.field === 'status'">
                <span v-if="scope.row[col.field]" class="table-status-active">启用</span>
                <span v-else class="table-status-inActive">禁用</span>
              </span>
              <span v-else>{{ scope.row[col.field] }}</span>
            </template>
          </el-table-column>
        </template>

        <!-- <el-table-column width="160" label="操作" align="center" class-name="table-operation" fixed="right">
          <template #default="scope">
            <el-button type="primary" link @click.stop="handleUpdate(scope.row)" v-if="!scope.row.status">
              修改
            </el-button>
            <div class="splitLine" v-if="!scope.row.status" v-has-perm="['sys:user:enable', 'sys:user:disable']"></div>
            <el-button type="primary" link v-if="!scope.row.status" @click="handleDel(scope.row)">
              删除
            </el-button>
          </template>
        </el-table-column>
        <template v-slot:empty>
          <svg-icon icon-class="noData" width="160px" height="160px" />
        </template> -->
      </el-table>
      <pagination v-if="total > 0" :total="total" v-model:pageNumTo="queryParams.pageNum"
        v-model:pageSizeTo="queryParams.pageSize" @pagination="handleQuery" />
    </div>

    <!--  分配角色  -->
    <el-drawer v-model="roleDialog.visible" @close="cancelRoleDialog" @opened="roleDialogOpend"
      class="drawer-show-table" modal-class="userRoleModel">
      <template #header>
        <div class="drawer-show-table-title">
          <svg-icon icon-class="close" width="20px" height="20px" @click="cancelRoleDialog" />
          <span>{{ roleDialog.title }}</span>
        </div>
        <el-button type="primary" @click="submitUserRole()">确 定</el-button>
      </template>
      <el-table border ref="roleTableRef" :data="allRole" highlight-current-row row-key="dataId" style="width: 100%">
        <el-table-column type="selection" width="40" align="center" />
        <el-table-column prop="code" label="角色编码" show-overflow-tooltip></el-table-column>
        <el-table-column prop="name" label="角色名称" show-overflow-tooltip></el-table-column>
        <el-table-column prop="remark" label="备注" show-overflow-tooltip></el-table-column>
      </el-table>
    </el-drawer>
  </div>
</template>

<script lang="ts">
export default {
  name: 'customManagement'
};
</script>

<script lang="ts" setup>
import { reactive, ref, onMounted, toRefs, getCurrentInstance, nextTick } from 'vue';
import { ElForm, ElMessageBox, ElTable } from 'element-plus';
import { addUser, updateUser, getUserRoleList, updateUserRole } from '@/api/user';
import { getRSAPublic } from '@/api/auth';
import { JSEncrypt } from 'jsencrypt'
import { getQueryList, BpelEvent, getQueryPageList } from '@/api/common';
import { customAdd, customDel, customUpd } from '@/api/basics/custom';
import { bTableHeight } from "../../../../composables/calcTableHeight";

const { tableContainer, tableHeight, updateTableHeight, handleResize } = bTableHeight(180);
const queryFormRef = ref(ElForm);
const formDataRef = ref(ElForm);
const { proxy }: any = getCurrentInstance();
//状态：判断是修改还是添加
let statuButton = 0;
const roleTableRef = ref<InstanceType<typeof ElTable>>();
const formDataRefData = ref({
  SITENAME: 'SDK',
  CUSTOMERNO: '',
  CUSTOMERNAME: '',
  DESCRIPTION: '',
  ADDRESS: '',
  DESTINATION: '',
  TEL: '',
  FAX: '',
  EMAIL: '',
  INCHARGE: '',
})
const state = reactive({
  disableds : false,
  loadings : false,
  rsa: '',
  DBProcessType: 'save',
  queryParams: {
    queryId: 'GetCustomerList',
    version: 'WEB10001',
    params: {
      CUSTOMERNO: '',
      CUSTNO: '',
      CUSTOMERNAME: ''
    },
    pageNum: 1,
    pageSize: 10,
  },
  ChangeParams: {
    header: {
      messageName: '',
      LANGUAGE: 'Chinese',
    },
    body: {
      SITENAME: 'SDK',
      CUSTOMERNO: '',
      CUSTOMERNAME: '',
      DESCRIPTION: '',
      ADDRESS: '',
      DESTINATION: '',
      TEL: '',
      FAX: '',
      EMAIL: '',
      INCHARGE: '',
    }
  },
  total: 0,
  loading: false,
  customerList: [] as any,
  dialog: {
    title: '新增用户',
    visible: false
  },
  formData: {
    CUSTOMERNO: '',
    CUSTOMERNAME: '',
    DESCRIPTION: '',
    DESTINATION: '',
    ADDRESS: '',
    TEL: '',
    FAX: '',
    EMAIL: '',
    INCHARGE: '',

  } as any,
  rules: {
    account: [{ required: true, message: '请输入账号', trigger: 'blur' }],
    name: [{ required: true, message: '请输入姓名', trigger: 'blur' }],
    pwd: [{ required: true, message: '请输入密码', trigger: 'blur' }],
  },
  column: [] as any,
  selectItem: undefined as any,
  currentTime: '',
  roleDialog: {
    title: '分配角色',
    visible: false
  },
  allRole: [] as any
})
const {
  rsa,
  queryParams,
  total,
  loading,
  userList,
  dialog,
  formData,
  rules,
  column,
  selectItem,
  currentTime,
  roleDialog,
  allRole
} = toRefs(state);

onMounted(() => {
  state.column = [
    { header: '客户编号', field: 'CUSTOMERNO', hide: false },
    { header: '客户名称', field: 'CUSTOMERNAME', hide: false },
    { header: '客户简称', field: '', hide: false },
    { header: '客户地址', field: 'ADDRESS', hide: false },
    { header: '供应商', field: '', hide: false },
    { header: '对应供应商', field: '', hide: false },

  ]
  // 初始化时调用 handleQuery  
  handleQuery();
  updateTableHeight();
  window.addEventListener('resize', handleResize);
});

function queryInfo() {
  state.queryParams.pageNum = 1
  handleQuery()
}
// 更新列
function updateList(col: any) {
  state.column = col;
}
function getRSA() {
  getRSAPublic().then((res: any) => {
    state.rsa = res.data;
  }).catch(() => { });
}
function handleQuery() {
  state.disableds = true;
  state.loadings = true;
  state.customerList = [];
  console.log(state.queryParams.params.CUSTOMERNO);
  getQueryPageList(state.queryParams)
    .then((res: any) => {
      console.log(res.data);
      if(res.data.list.length == 0){
        ElMessageBox.alert('查无数据', '提醒框', {
          confirmButtonText: 'OK',
        })
        state.disableds = false;
        state.loadings = false;
      } else {
        state.customerList = res.data.list;
        state.total = res.data.total;
        state.disableds = false;
        state.loadings = false;
      }
    })
    .catch(() => { });
}
function resetQuery() {
  state.queryParams.params.CUSTOMERNO = '';
  state.queryParams.params.CUSTOMERNAME = '';
  state.queryParams.params.CUSTNO = '';
  queryFormRef.value.resetFields();
  handleQuery();
}
function showCurrentTime() {
  let date = new Date()
  state.currentTime = date.getFullYear() + '-' + (date.getMonth() + 1) + '-' + date.getDate() + ' ' + date.getHours() + ":" +
    (date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes()) + ":" + (date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds())
}

/**
 * 新增供应商用户 dialog
 */
function handleAdd() {
  selectItem.value = undefined;
  dialog.value = {
    title: '新增客户',
    visible: true
  };
  state.rules.pwd[0].required = true;
  statuButton = 2;
}

/**
 * 删除供应商用户 dialog
 */
function handleDel(row: any) {
  customDel(row)
    .then((res: any) => {
      showCurrentTime();
      handleQuery();
    }).then(() => proxy.$ElMessage.success('删除成功'))
    .catch(() => { });
}

/**
 * 修改供应商用户 dialog
 */
function handleUpd() {

}
/**
 * 编辑用户 dialog
 */
function handleUpdate(row: any) {
  state.dialog = {
    title: '编辑客户',
    visible: true
  };
  state.selectItem = row;
  state.rules.pwd[0].required = false;
  statuButton = 1;
}

function dialogOpend() {
  formDataRef.value.resetFields();
}

/**
 * 取消关闭弹窗
 */
function cancel() {
  state.dialog.visible = false;
}

/**
 * 保存
 */
function submitForm() {
  console.log(state.formData);
  switch (statuButton) {
    case 0: break;
    case 1: customUpd(state.formData)
      .then((res: any) => {
        console.log("upd" + res.code + ":" + statuButton + ":state.formData");
        dialog.value.visible = false;
        handleQuery();
      }).then(() => proxy.$ElMessage.success('修改成功'))
      .catch(() => { }); break;
    case 2: customAdd(state.formData)
      .then((res: any) => {
        console.log("Add:" + res.code + ":" + statuButton);
        dialog.value.visible = false;
      }).then(() => proxy.$ElMessage.success('创建成功'))
      .catch(() => { }); break;
  }
  statuButton = 0;
}
/****************************** 分配角色 ***************************/
function handleRole(row: any) {
  state.roleDialog.visible = true;
  state.allRole = [];
  state.selectItem = row;
}
function cancelRoleDialog() {
  state.roleDialog.visible = false;
}
function roleDialogOpend() {
  getUserRoleList({
    dataId: state.selectItem.dataId
  })
    .then((res: any) => {
      state.allRole = res.data.list;
      let rows = state.allRole.filter((item: any) => res.data.checked.includes(item.dataId));
      rows.forEach((item: any) => {
        console.log(item);
        nextTick(() => {
          roleTableRef.value!.toggleRowSelection(item, true);
        })
      })
    })
    .catch(() => { });
}
function submitUserRole() {
  let checkedRole = [] as any;
  roleTableRef.value!.getSelectionRows().forEach((item: any) => {
    checkedRole.push(item.dataId);
  })
  let params = {
    dataId: state.selectItem.dataId,
    relIds: checkedRole,
  }
  updateUserRole({
    data: params
  })
    .then((res: any) => {
      proxy.$ElMessage.success('关联成功');
      cancelRoleDialog();
      handleQuery();
    })
    .catch(() => { });
}
const buildInfo = () => { state.DBProcessType = 'Insert' }
const editInfo = () => { state.DBProcessType = 'Update' }
/* 功能：保存创建修改信息 
   参数：ChangeParams
   时间：:2024-4-24
   作者：李文虎
*/
const saveInfo = () => {
  if (state.DBProcessType == 'Insert') {
    state.ChangeParams.header.messageName = 'CreateCustomer'
  } else if (state.DBProcessType == 'Update') {
    state.ChangeParams.header.messageName = 'ModifyCustomer'
  }
  BpelEvent(state.ChangeParams).then((res: any) => {

  })
    .catch(() => { });
}
const exiteInfo = () => {
  formDataRef.value.resetFields()
}
</script>

<style scoped lang="scss"></style>
