<template>
  <BasicDrawer title="数据规则/按钮权限配置" :width="365" @close="onClose" @register="registerDrawer">
    <Spin :spinning="loading">
      <Tabs defaultActiveKey="1">
        <TabPane tab="数据规则" key="1">
          <CheckboxGroup v-model:value="dataRuleChecked" v-if="dataRuleList.length > 0">
            <Row>
              <Col :span="24" v-for="(item, index) in dataRuleList" :key="'dr' + index">
                <Checkbox :value="item.id">{{ item.ruleName }}</Checkbox>
              </Col>
              <Col :span="24">
                <div style="width: 100%; margin-top: 15px">
                  <c-button
                    type="primary"
                    :loading="loading"
                    :size="'small'"
                    preIcon="ant-design:save-filled"
                    @click="saveDataRuleForRole"
                  >
                    <span>点击保存</span>
                  </c-button>
                </div>
              </Col>
            </Row>
          </CheckboxGroup>
          <Empty v-else description="无配置信息" />
        </TabPane>
        <!--<a-tab-pane tab="按钮权限" key="2">敬请期待!!!</a-tab-pane>-->
      </Tabs>
    </Spin>
  </BasicDrawer>
</template>

<script lang="ts" setup>
  import { ref, unref } from 'vue';
  import { BasicDrawer, useDrawerInner } from '@jdlinker/ui';
  import { queryDepartRoleDataRule, saveDepartRoleDataRule } from '../depart.user.api';
  import { Spin, Tabs, TabPane, CheckboxGroup, Row, Col, Checkbox, Empty } from 'ant-design-vue';

  defineEmits(['register']);
  const loading = ref<boolean>(false);
  const departId = ref('');
  const functionId = ref('');
  const roleId = ref('');
  const dataRuleList = ref<Array<any>>([]);
  const dataRuleChecked = ref<Array<any>>([]);

  // 注册抽屉组件
  const [registerDrawer] = useDrawerInner((data) => {
    roleId.value = unref(data.roleId);
    departId.value = unref(data.departId);
    functionId.value = unref(data.functionId);
    loadData();
  });

  async function loadData() {
    try {
      loading.value = true;
      const { datarule, drChecked } = await queryDepartRoleDataRule(functionId, departId, roleId);
      dataRuleList.value = datarule;
      if (drChecked) {
        dataRuleChecked.value = drChecked.split(',');
      }
    } finally {
      loading.value = false;
    }
  }

  function saveDataRuleForRole() {
    let params = {
      permissionId: functionId.value,
      roleId: roleId.value,
      dataRuleIds: dataRuleChecked.value.join(',')
    };
    saveDepartRoleDataRule(params);
  }

  function onClose() {
    doReset();
  }

  function doReset() {
    functionId.value = '';
    roleId.value = '';
    dataRuleList.value = [];
    dataRuleChecked.value = [];
  }
</script>
