<template>
  <a-drawer
    :width="width"
    placement="right"
    :closable="true"
    @close="handleCancel"
    :keyboard="false"
    :body-style="{ padding: '5px 24px 64px 24px' }"
    :maskClosable="false"
    v-model:open="visible"
  >
    <template #title>
      <span v-if="onlyUser"> 负责区域 </span>
      <span v-else
        >{{ title }}
        <span style="float: right; margin: -3px 20px 0 0"
          >分配给：
          <a-select v-model:value="user" style="width: 180px">
            <a-select-option v-for="item in userList" :key="item.id" :value="item.id">
              {{ item.username }}
            </a-select-option>
          </a-select>
        </span>
      </span>
    </template>

    <a-tree
      checkable
      v-if="treeData.length"
      :tree-data="treeData"
      v-model:checked-keys="checkdNode"
      class="self-tree"
      :defaultExpandAll="true"
      :blockNode="false"
      @check="onCheck"
    />

    <a-empty v-if="treeData.length == 0" />

    <div class="drawer-footer">
      <a-button @click="handleCancel" style="margin-bottom: 0">关闭</a-button>
      <a-button :loading="loading" @click="handleOk" type="primary" style="margin-bottom: 0" v-if="treeData.length > 0">
        {{ onlyUser ? '保存修改' : '确认分配' }}</a-button
      >
    </div>
  </a-drawer>
</template>

<script lang="ts" setup>
  import { getAction, postAction } from '/@/api/manage/manage';
  import { useMessage } from '@/hooks/web/useMessage';
  import { ref } from 'vue';

  const { createMessage } = useMessage();

  const title = ref('待分配区域');
  const width = 700;
  const onlyUser = ref(false);
  const visible = ref(false);

  let treeData = ref([]);
  let checkdNode = ref([]);
  let userList = ref([{ id: '', username: '' }]);
  const user = ref('');
  const id = ref('');
  const loading = ref(false);
  const siteId = ref('');

  // 定义父组件的方法, 子组件调用父组件的方法
  const emit = defineEmits(['ok']);

  function reload() {
    visible.value = true;
    treeData.value = [];
    checkdNode.value = [];
    userList.value = [];
    user.value = '';
    loading.value = false;
  }

  function init(siteIdParam) {
    siteId.value = siteIdParam;
    reload();
    onlyUser.value = false;
    getAllTree();
  }

  function getAllTree() {
    checkdNode.value = [];
    id.value = '';
    getAction('/usercountry/country/uncontribute?siteId=' + siteId.value, {}).then((res) => {
      if (res.code == 200) {
        treeData.value = res.result == null ? [] : res.result;

        console.log(treeData, 'treeDatatreeData');
      }
    });

    getAction('/usercountry/subAccounts/optionswithoutself', {}).then((res) => {
      if (res.code == 200) {
        userList.value = res.result;
        user.value = res.result.length > 0 ? res.result[0].id : '';
      }
    });
  }

  //子账户直接进入获取到所有的已分配国家
  function getUsersTree(idParam, siteIdParam) {
    siteId.value = siteIdParam;
    reload();
    onlyUser.value = true;
    id.value = idParam;
    checkdNode.value = [];
    getAction('/usercountry/country/charge?id=' + id.value + '&siteId=' + siteId.value, {}).then((res) => {
      if (res.code == 200) {
        treeData.value = res.result == null ? [] : res.result;
        if (treeData.value.length > 0) {
          for (let i in res.result) {
            checkdNode.value.push(res.result[i].key);
            for (let j in res.result[i].children) {
              checkdNode.value.push(res.result[i].children[j].key);
            }
          }
        }
      }
    });
  }

  function onCheck() {
    console.log('onCheck', checkdNode);
  }

  function handleCancel() {
    visible.value = false;
  }

  function handleOk() {
    console.log(user.value, ' user.value', id.value, ' id.value');

    if (user.value == '' && id.value == '') {
      createMessage.warn('请先选择要分配的子用户');
      return;
    }

    let d = {
      uid: user.value == '' ? id.value : user.value,
      countryIds: checkdNode.value.toString(),
      siteId: siteId.value,
    };
    let url = onlyUser.value ? '/usercountry/contribute/delete' : '/usercountry/contribute/add';
    loading.value = true;
    postAction(url, d, 120000).then((res) => {
      loading.value = false;
      if (res.code == 200) {
        createMessage.success('分配成功');
        emit('ok');
        if (onlyUser.value) {
          getUsersTree(id, siteId);
        } else {
          getAllTree();
        }
      } else {
        if (res.code == 403) {
          createMessage.warning(res.message);
        } else {
          createMessage.error('分配失败');
        }
      }
    });
  }

  // 暴漏子组件方法，引用该组件的父组件可直接调用该方法
  defineExpose({ init, getUsersTree });
</script>

<style lang="less" scoped>
  /** Button按钮间距 */
  .ant-btn {
    margin-left: 30px;
    margin-bottom: 30px;
    float: right;
  }

  .drawer-footer {
    position: absolute;
    bottom: 0px;
    width: 100%;
    border-top: 1px solid #e8e8e8;
    padding: 10px 16px;
    text-align: right;
    left: 0;
    background: #fff;
    border-radius: 0 0 2px 2px;
  }
</style>

<style lang="less">
  .self-tree {
    .ant-tree-child-tree {
      width: 100%;
      display: block;
      overflow: hidden;
      li {
        width: 33.33%;
        float: left;
        display: inline-block;
        padding: 5px 0;
      }
    }
  }
</style>
