<template>
  <a-card :bordered="false">
    <!-- 查询区域 -->
    <div class="table-page-search-wrapper">
      <a-form layout="inline" @keyup.enter.native="searchQuery" style="display: block">
        <a-row :gutter="24">
          <a-col :md="6" :sm="12">
            <a-form-item>
              <a-input placeholder="请输入用户账号/用户名/手机号" v-model:value="queryParam.queryCondition" />
            </a-form-item>
          </a-col>
          <a-col :md="18" :sm="12">
            <span style="float: left; overflow: hidden" class="table-page-search-submitButtons">
              <a-button type="primary" @click="searchQuery" preIcon="ant-design:search-outlined">查询</a-button>
              <a-button ghost type="primary" @click="searchReset" preIcon="ant-design:reload-outlined" style="margin-left: 8px">重置</a-button>
              <a-button ghost @click="handleAdd" type="primary" style="margin-left: 8px" preIcon="ant-design:plus-outlined">添加子用户</a-button>
              <a-button ghost type="primary" @click="showRecycleBin" style="margin-left: 8px" preIcon="ant-design:hdd-outlined">回收站</a-button>
              <router-link :to="{ path: '/inquery/rules' }" v-if="siteCode !== dictSiteCode">
                <a-button ghost type="primary" preIcon="ant-design:logout-outlined" @click="showRecycleBin" style="margin-left: 8px"
                  >配置询盘规则</a-button
                >
              </router-link>
            </span>
          </a-col>
        </a-row>
      </a-form>
    </div>

    <!-- table区域-begin -->
    <div v-if="siteCode !== dictSiteCode">
      <BasicTable @register="registerTable" :rowSelection="rowSelection">
        <template #action="{ record }">
          <div style="padding: 8px; display: flex; justify-content: space-evenly">
            <a-tag color="purple" @click="handleEdit(record)" style="cursor: pointer"> 编辑 </a-tag>
            <a-tag color="green" @click="handleChangePassword(record.username)" style="cursor: pointer"> 重置密码 </a-tag>
            <a-popconfirm v-if="!record.primaryAccount" title="确定删除吗?" @confirm="() => handleFrozen(record.id, 2)">
              <a-tag color="red" style="cursor: pointer"> 删除 </a-tag>
            </a-popconfirm>
          </div>
        </template>
      </BasicTable>
    </div>
    <!-- table区域-end -->

    <!--    table-子账户轮询-begin-->
    <div v-if="siteCode === dictSiteCode">
      <h1>关闭配置或新增子账号会重置轮流分配</h1>
      <a-table
        ref="table"
        size="middle"
        rowKey="id"
        :scroll="{ x: true }"
        :columns="subColumns"
        :dataSource="subAccountList"
        :pagination="ipagination1"
        :loading="loading"
        @change="handleTableChange"
      >
        <template #avatarslot="text, record, index">
          <div class="anty-img-wrap" style="margin-bottom: 5px">
            <a-avatar shape="square" :src="getAvatarView(record.avatar)" icon="user" />
          </div>
        </template>

        <template #action="text, record">
          <span>
            <div>
              <a-switch
                :checked="record.isInquiry === 2"
                @change="(checked) => handleSwitchChange(record, checked)"
                checked-children="开"
                un-checked-children="关"
                :disabled="record.primaryAccount"
              />
            </div>
          </span>
        </template>

        <template #action1="text, record">
          <span>
            <div style="padding: 8px">
              <a-tag color="purple" @click="handleEdit(record)" style="cursor: pointer"> 编辑 </a-tag>
              <!--            <a-tag v-if="!record.primaryAccount" color="orange" @click="handlePerssion(record.id)" style="cursor:pointer;">-->
              <!--              菜单配置-->
              <!--            </a-tag>-->
              <a-tag color="green" @click="handleChangePassword(record.username)" style="cursor: pointer"> 重置密码 </a-tag>
              <a-popconfirm v-if="!record.primaryAccount" title="确定删除吗?" @confirm="() => handleFrozen(record.id, 2)">
                <a-tag color="red" style="cursor: pointer"> 删除 </a-tag>
              </a-popconfirm>
            </div>
          </span>
        </template>
        <template #countSlot="text, record, index">
          <span style="margin-left: 20px">{{ text }} 个</span>
        </template>
      </a-table>
    </div>
    <!--    table-子账户轮询-begin-->

    <!-- 编辑、新增用户 -->
    <enterprise-user-modal ref="registerModal" @ok="modalFormOk" />

    <!--修改密码-->
    <PasswordModal @register="registerPasswordModal" @success="reload" />

    <!-- 用户回收站 -->
    <enterprise-user-recycle-bin-modal ref="recycleBin" @ok="modalFormOk" />
  </a-card>
</template>

<script lang="ts" setup>
  import '@/assets/less/common.less';
  import EnterpriseUserModal from './modules/EnterpriseUserModal.vue';

  import { getAction, getFileAccessHttpUrl, putAction } from '@/api/manage/manage';
  import EnterpriseUserRecycleBinModal from './modules/EnterpriseUserRecycleBinModal.vue';
  import PasswordModal from '/@/views/system/user/PasswordModal.vue';

  import { onBeforeMount, reactive, ref } from 'vue';
  import { BasicTable } from '@/components/Table';
  import { useMessage } from '@/hooks/web/useMessage';
  import { useListPage } from '@/hooks/system/useListPage';
  import { deleteOne, list } from '@/views/adweb/enterprise/EnterpriseUserManage.api';
  import { columns, subColumns } from '@/views/adweb/enterprise/EnterpriseUserManage.data';
  import { useModal } from '@/components/Modal';

  let subAccountList = reactive([]);
  const registerModal = ref();
  const recycleBin = ref();
  const ipagination1 = reactive({
    current: 1,
    pageSize: 10,
    pageSizeOptions: ['10', '20', '30'],
    showTotal: (total, range) => {
      return range[0] + '-' + range[1] + ' 共' + total + '条';
    },
  });
  let queryParam = reactive<any>({});
  const loading = ref(false);
  const siteCode = ref();
  const dictSiteCode = ref();

  const { createMessage } = useMessage();
  //注册table数据
  const { prefixCls, tableContext } = useListPage({
    tableProps: {
      title: '账户管理',
      api: list,
      columns,
      canResize: false,
      useSearchForm: false,
      actionColumn: {
        width: 180,
        fixed: 'right',
      },
      striped: true,
      bordered: false,
      immediate: true, // 不直接触发，通过reload事件触发接口
      beforeFetch: (params) => {
        return Object.assign(params, queryParam);
      },
    },
  });
  const [
    registerTable,
    { reload, clearSelectedRowKeys, updateTableDataRecord, findTableDataRecord, getDataSource },
    { rowSelection, selectedRowKeys },
  ] = tableContext;

  const [registerPasswordModal, { openModal: openPasswordModal }] = useModal();

  onBeforeMount(() => {
    subList();
    siteCode.value = localStorage.getItem('siteCode');
    getTurnInquiryCode();
  });

  //获取需要轮流询盘的站点code
  function getTurnInquiryCode() {
    getAction('/adweb/adwebEnquiry/getTurnInquiryCode', {}).then((res) => {
      if (res.code === 200) {
        dictSiteCode.value = res.result[0].value;
      }
    });
  }
  function handleFrozen(id, status) {
    loading.value = true;
    putAction('/enterprise/user/frozen', { ids: id, status: status }).then((res) => {
      if (res.success) {
        createMessage.success(res.message);
        if (siteCode.value === dictSiteCode.value) {
          subList();
        } else {
          reload();
        }
      } else {
        createMessage.warning(res.message);
      }
      loading.value = false;
    });
  }
  function getAvatarView(avatar) {
    return getFileAccessHttpUrl(avatar, 'https');
  }
  function showRecycleBin() {
    recycleBin.value.show();
  }
  function searchQuery() {
    if (siteCode.value === dictSiteCode.value) {
      subList();
    } else {
      reload();
    }
    clearSelectedRowKeys();
  }
  function searchReset() {
    queryParam = {};
    if (siteCode.value === dictSiteCode.value) {
      subList();
    } else {
      reload();
    }
  }

  /**
   * 打开修改密码弹窗
   */
  function handleChangePassword(username) {
    openPasswordModal(true, { username });
  }

  function handlePerssion(userId) {
    this.$refs.modalUserRole.show(userId);
  }

  function modalFormOk() {
    // 新增/修改 成功时，重载列表
    if (siteCode.value === dictSiteCode.value) {
      subList();
    } else {
      reload();
    }
  }
  //获取子账户
  function subList() {
    let params = queryParam;
    params.siteCode = localStorage.getItem('siteCode');
    getAction('/enterprise/user/sub/list', params).then((res) => {
      if (res.success) {
        subAccountList = res.result.records;
        ipagination1.total = res.result.total;
      }
      if (siteCode.value === dictSiteCode.value) {
        loading.value = false;
      }
    });
  }
  function handleSwitchChange(record, checked) {
    // 处理开关切换操作
    record.isInquiry = checked ? 2 : 1;
    putAction('/enterprise/user/updateIsInquiry', record).then((res) => {
      if (res.success) {
        createMessage.success(res.message);
        subList();
      } else {
        createMessage.warning(res.message);
        subList();
      }
    });
  }

  /**
   * 新增事件
   */
  function handleAdd() {
    registerModal.value.disableSubmit = false;
    registerModal.value.title = '新增';
    registerModal.value.add();
  }

  /**
   * 编辑事件
   */
  function handleEdit(record: Recordable) {
    registerModal.value.disableSubmit = false;
    registerModal.value.edit(record);
  }

  /**
   * 删除事件
   */
  async function handleDelete(record) {
    await deleteOne({ id: record.id }, handleSuccess);
  }

  /**
   * 成功回调
   */
  function handleSuccess() {
    (selectedRowKeys.value = []) && reload();
  }
</script>
