<template>
  <div class="content adweb-enquiry-distribution">
    <a-spin :tip="loadingTip" :spinning="loadingStatus">
      <div class="spin-content">
        <a-row class="r0" :gutter="8" style="margin-bottom: 16px">
          <a-col :xl="7" :xxl="6">
            <div class="choose-site">
              <span class="t1">站点：</span>
              <select-site ref="selectSiteRef" @set-site-info="changeSite" select-width="100%" />
            </div>
          </a-col>
        </a-row>
        <a-row class="r1">
          <a-col :xl="19" :xxl="20">
            <a-row>
              <a-col :span="24"><p class="title">分配规则：</p></a-col>
              <a-col :span="8" :class="rulesOptions == 'MASTER' ? 'active' : ''">
                <p class="t1">
                  <img @click="changeRules('MASTER')" class="chooseImg" :src="rulesOptions == 'MASTER' ? checkImg : uncheckImg" alt="" />
                  仅主账户可见
                </p>
                <p class="t2">(只有主账户可以查看询盘信息)</p>
              </a-col>
              <a-col :span="8" :class="rulesOptions == 'ALL' ? 'active' : ''">
                <p class="t1">
                  <img @click="changeRules('ALL')" class="chooseImg" :src="rulesOptions == 'ALL' ? checkImg : uncheckImg" alt="" />
                  完全开放
                </p>
                <p class="t2">(客户主账号和员工账号均可在后台查看该站点所有询盘)</p>
              </a-col>
              <a-col :span="8" :class="rulesOptions == 'REGION' ? 'active' : ''">
                <p class="t1">
                  <img @click="changeRules('REGION')" class="chooseImg" :src="rulesOptions == 'REGION' ? checkImg : uncheckImg" alt="" />
                  按买家地域分配
                </p>
                <p class="t2">(系统根据买家的国家，将询盘自动分配给对应的账号)</p>
              </a-col>
            </a-row>
          </a-col>
          <a-col
            :xl="5"
            :xxl="4"
            v-if="!(userRole.indexOf('admin') > -1 || userRole.indexOf('adweb_site_manager') > -1 || userRole.indexOf('adweb_seo_manager') > -1)"
          >
            <router-link :to="{ path: '/enterprise/enterpriseUser' }">
              <div class="add-account">
                <a-icon type="user" />
                <p>新增子账户</p>
              </div>
            </router-link>
          </a-col>
        </a-row>
        <a-row class="r2" v-if="rulesOptions == 'REGION'">
          <a-col :span="24">
            <p class="tips">说明：系统根据买家的国家，将询盘自动分配给对应的账号，不能确定买卖国家或相关国家没有被分配的，将统一分配给主账号。</p>
            <a-button type="primary" style="margin-bottom: 10px" @click="showDistributionArea">待分配区域</a-button>
          </a-col>

          <a-col :span="24">
            <a-table
              ref="table"
              size="middle"
              :scroll="{ x: true }"
              rowKey="id"
              :columns="columns"
              :dataSource="dataSource"
              :pagination="false"
              :loading="loading"
              class="j-table-force-nowrap"
            >
              <template #bodyCell="{ column, record }">
                <template v-if="column.dataIndex === 'action'">
                  <a-button v-if="record.id !== '-1'" type="primary" @click="getUsersTree(record.id)">负责区域</a-button>
                  <span v-else>--</span>
                </template>
              </template>
            </a-table>
          </a-col>
        </a-row>
        <a-row class="r1">
          <a-col :xl="19" :xxl="20">
            <a-row>
              <a-col :span="24"><p class="title">邮件发送规则：</p></a-col>
              <a-col :span="8" :class="sendEmailOptions == 'MASTER' ? 'active' : ''">
                <p class="t1">
                  <img @click="changeSendEmailRules('MASTER')" class="chooseImg" :src="sendEmailOptions == 'MASTER' ? checkImg : uncheckImg" />
                  仅主账户
                </p>
                <p class="t2">(只有主账户邮箱可以收到询盘邮件)</p>
              </a-col>
              <a-col :span="8" :class="sendEmailOptions == 'ALL' ? 'active' : ''">
                <p class="t1">
                  <img @click="changeSendEmailRules('ALL')" class="chooseImg" :src="sendEmailOptions == 'ALL' ? checkImg : uncheckImg" />
                  所有人
                </p>
                <p class="t2">(客户主账号和员工账号邮箱均可收到询盘邮件)</p>
              </a-col>
            </a-row>
          </a-col>
        </a-row>
      </div>
    </a-spin>
    <distribution-area @ok="modalFormOk" ref="distributionAreaRef" />
  </div>
</template>

<script lang="ts" setup>
  import distributionArea from './modules/distributionArea.vue';
  import checkImg from '/@/assets/enquiry/enquiryRules/checked.svg';
  import uncheckImg from '/@/assets/enquiry/enquiryRules/uncheck.svg';
  import { getAction, postAction } from '/@/api/manage/manage';
  import selectSite from '/@/components/Adweb/selectSite.vue';
  import { nextTick, onMounted, reactive, ref } from 'vue';
  import { useUserStore } from '@/store/modules/user';
  import { useMessage } from '@/hooks/web/useMessage';
  import { Modal } from 'ant-design-vue';
  const { userInfo } = useUserStore();
  const queryParam = reactive<any>({});
  const rulesOptions = ref('');
  const sendEmailOptions = ref('');
  const columns = [
    {
      title: '企业名称',
      align: 'center',
      dataIndex: 'realname',
    },
    {
      title: '登录账号',
      align: 'center',
      dataIndex: 'username',
    },
    {
      title: '已分配国家',
      align: 'center',
      dataIndex: 'countryNum',
      customRender: function (text) {
        return text >= 0 ? text : '-';
      },
    },
    {
      title: '询盘数',
      align: 'center',
      dataIndex: 'enquiryNum',
    },
    {
      title: '操作',
      align: 'center',
      dataIndex: 'action',
      scopedSlots: {
        customRender: 'action',
      },
    },
  ];
  const url = {
    list: '/usercountry/subAccounts',
  };
  let dataSource = reactive([]);
  const loading = ref(false);
  const distributionAreaRef = ref();

  const siteId = ref();

  let userRole = ref<String>('');
  const loadingTip = ref('');
  const loadingStatus = ref(false);
  const { createMessage } = useMessage();

  const ipagination = {
    current: 1,
    pageSize: 30,
    pageSizeOptions: ['15', '30', '50', '100'],
    showTotal: (total, range) => {
      return range[0] + '-' + range[1] + ' 共' + total + '条';
    },
    showQuickJumper: true,
    showSizeChanger: true,
    total: 0,
  };

  onMounted(() => {
    console.log(userInfo?.roles, 'userInfo?.roles');
    userRole.value = userInfo?.roles.join(',');
  });

  function changeSite(selectedSiteInfo: any) {
    loadingTip.value = '切换站点中...';
    loadingStatus.value = true;
    siteId.value = selectedSiteInfo.id;
    dealSiteData();
  }
  //处理站点数据
  function dealSiteData() {
    let param = {
      siteId: siteId.value,
    };
    getAction('/usercountry/getSiteBySiteId', param)
      .then((res) => {
        if (res.code == 200) {
          let data = res.result;
          //获取并处理站点分配规则
          rulesOptions.value = data.enquiryDistributeType;
          if (data.enquiryDistributeType === 'REGION') {
            queryParam.siteId = siteId;
            loadData(1);
          }

          //获取站点的发送邮箱规则
          sendEmailOptions.value = data.enquirySendEmailType;
        }
      })
      .finally(() => {
        loadingStatus.value = false;
        loadingTip.value = '';
      });
  }
  //改变分配规则
  function changeRules(e) {
    if (
      userRole.value.indexOf('admin') > -1 ||
      userRole.value.indexOf('adweb_site_manager') > -1 ||
      userRole.value.indexOf('adweb_seo_manager') > -1
    ) {
      createMessage.warning('管理员账号不可修改分配规则！');
      return;
    }

    Modal.confirm({
      title: '修改分配规则',
      content: `您确定要修改吗？`,
      centered: true,
      onOk: () => {
        loadingTip.value = '改变分配规则中，请稍等...';
        loadingStatus.value = true;
        postAction('/usercountry/updateDistributeType?distributeType=' + e + '&siteId=' + siteId.value, {}, 60000)
          .then((res) => {
            if (res.success) {
              rulesOptions.value = e;
              if (e === 'REGION') {
                queryParam.siteId = siteId;
                loadData(1);
              }
            } else {
              if (res.code == 403) {
                createMessage.warning(res.message);
              } else {
                createMessage.error('修改失败，请联系管理员');
              }
            }
          })
          .finally(() => {
            loadingStatus.value = false;
            loadingTip.value = '';
          });
      },
    });
  }

  function showDistributionArea() {
    nextTick(() => {
      distributionAreaRef.value.init(siteId.value);
    });
  }

  function getUsersTree(id) {
    nextTick(() => {
      console.log(id, siteId.value, 'id, siteId.value');

      distributionAreaRef.value.getUsersTree(id, siteId.value);
    });
  }

  //改变邮箱接收邮件规则
  function changeSendEmailRules(e) {
    if (
      userRole.value.indexOf('admin') > -1 ||
      userRole.value.indexOf('adweb_site_manager') > -1 ||
      userRole.value.indexOf('adweb_seo_manager') > -1
    ) {
      createMessage.warning('管理员账号不可修改分配规则！');
      return;
    }

    Modal.confirm({
      title: '修改邮件发送规则',
      content: `您确定要修改吗？`,
      centered: true,
      onOk: () => {
        loadingTip.value = '改变邮件规则中，请稍等...';
        loadingStatus.value = true;
        postAction('/usercountry/updateSendEmailType?sendEmailType=' + e + '&siteId=' + siteId.value, {}, 120000)
          .then((res) => {
            if (res.success) {
              sendEmailOptions.value = e;
            } else {
              if (res.code == 403) {
                createMessage.warning(res.message);
              } else {
                createMessage.error('修改失败，请联系管理员');
              }
            }
          })
          .finally(() => {
            loadingStatus.value = false;
            loadingTip.value = '';
          });
      },
    });
  }

  function modalFormOk() {
    // 新增/修改 成功时，重载列表
    loadData(0);
  }

  function loadData(arg) {
    if (!url.list) {
      createMessage.error('请设置url.list属性!');
      return;
    }
    //加载数据 若传入参数1则加载第一页的内容
    if (arg === 1) {
      ipagination.current = 1;
    }

    loading.value = true;
    getAction(url.list, queryParam).then((res) => {
      if (res.success) {
        dataSource = res.result.records || res.result;
        if (res.result.total != 0) {
          ipagination.total = res.result.total;
        } else {
          ipagination.total = 0;
        }
      }
      if (res.code === 510) {
        createMessage.warning(res.message);
      }
      loading.value = false;
    });
  }
</script>

<style lang="less" scoped>
  :deep(.spin-content .ant-row) {
    margin: 15px 0;
  }

  .r0 {
    .choose-site {
      display: flex;
      align-items: center;

      :deep(.ant-select-selection) {
        background: transparent;
        color: #fff;
      }

      :deep(.ant-select-selection__clear) {
        background: transparent;
      }

      :deep(i),
      :deep(.ant-calendar-range-picker-separator) {
        color: #fff;
      }
    }

    .t1 {
      font-size: 18px;
    }

    .ant-calendar-picker {
      margin-right: 20px;

      :deep(.ant-input) {
        background: transparent;
        color: #e2e2e2;
      }
    }

    :deep(.ant-btn) {
      background: transparent;
      color: #e2e2e2;
      margin-right: 10px;

      &.active {
        background: #fff;
        border-color: #fff;
        color: @primary-color;
      }
    }
  }

  .r1 {
    background: #fff;
    border-radius: 10px;
    padding: 20px;
    color: #000;
    margin-bottom: 10px;
    .title {
      font-size: 18px;
      font-weight: 500;
      color: #000;
    }

    .t1 {
      color: #999;
      margin-bottom: 5px;
      font-size: 16px;

      .chooseImg {
        width: 20px;
        cursor: pointer;
        margin: -4px 10px 0 0;
      }
    }

    .t2 {
      color: #999;
      margin-bottom: 0;
      margin-left: 35px;
    }

    .active {
      .t1 {
        color: @primary-color;
      }

      .t2 {
        color: #000;
      }
    }

    .add-account {
      background: rgb(242, 248, 255);
      color: @primary-color;
      text-align: center;
      line-height: 1;
      display: flex;
      flex-direction: column;
      justify-content: center;
      align-items: center;
      height: 95px;
      border-radius: 10px;
      cursor: pointer;
      transition: all 0.3s;
      &:hover {
        background: @primary-color;
        a {
          color: #fff;
        }
        p {
          color: #fff;
        }
        :deep(svg) {
          color: #fff;
        }
      }

      i {
        padding-bottom: 10px;
      }

      p {
        margin-bottom: 0;
      }
    }
  }

  .r2 {
    background: #fff;
    border-radius: 10px;
    padding: 20px;
    color: #000;
    .tips {
      margin-bottom: 10px;
      color: #999;
      font-size: 13px;
    }
  }
</style>
