<template>
  <BasicModal v-bind="$attrs" @register="register" @ok="confirm" :title="title" minHeight="500">
    <BasicForm @register="registerForm" :model="model" />
    <!-- <MenuTree /> -->
    <div class="tree-wrap">
      <p class="tree-label">权限</p>
      <a-tree
        v-if="allowRule.length"
        checkable
        :tree-data="allowRule"
        showLine
        defaultExpandAll
        :replace-fields="replaceFields"
        v-model:checkedKeys="rules"
      />
    </div>
  </BasicModal>
</template>
<script lang="ts">
  import { Tree } from 'ant-design-vue';
  import { defineComponent, PropType, reactive, ref, toRefs } from 'vue';
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { BasicForm, useForm } from '/@/components/Form/index';
  import { schemas } from './data';
  import { getAllowRule } from '/@/api/sys/user';

  interface PopupData {
    title: string;
    treeData: object[];
  }
  interface AllowRule {
    id: number;
  }
  interface ReactData {
    id: number | string;
    allowRule: AllowRule[];
    initRules: number[];
    rules: number[];
    treeData: object[];
  }

  export default defineComponent({
    components: { BasicModal, BasicForm, [Tree.name]: Tree },
    props: {
      popupData: {
        type: Object as PropType<PopupData>,
        default: () => {},
      },
    },
    emits: ['saveData'],
    setup(props, { emit }) {
      const reactData = reactive<ReactData>({
        id: 0,
        allowRule: [],
        initRules: [],
        rules: [],
        treeData: [],
      });
      const popupData = props.popupData as PopupData;
      const modelRef = ref({});
      const replaceFields = {
        key: 'id',
      };
      //   watch(reactData, () => {
      //     console.log('rules', reactData.rules);
      //   });

      const [
        registerForm,
        { getFieldsValue, updateSchema, setFieldsValue, resetFields /* validate*/ },
      ] = useForm({
        labelWidth: 100,
        schemas,
        showActionButtonGroup: false,
        actionColOptions: { span: 24 },
      });
      const [register, { closeModal }] = useModalInner((data) => {
        console.log(data);
        console.log('data=========================');
        resetFields();
        // if (unref(isUpdate)) {
        //   setFieldsValue(data);
        // }
        if (data.id) {
          reactData.id = data.id;
        } else {
          reactData.id = 0;
          reactData.rules = [];
        }
        getRuleTree(data.pid);
        if (data.rules) {
          reactData.initRules = data.rules.split(',');
          reactData.initRules = reactData.initRules.map((item) => parseInt(item));
        }

        setFieldsValue(data);
        formatTreeData(popupData.treeData); // 禁止选取自己或自己下级为父id
        console.log(`popupData.treeData`, popupData.treeData);
        updateSchema({
          field: 'pid',
          componentProps: {
            onChange: (e: ChangeEvent) => {
              console.log('===========onChange1====ddd===');
              console.log(e);
              getRuleTree(e);
            },
            treeData: popupData.treeData,
          },
        });
      });

      function formatChildren(child) {
        child.map((item) => {
          item.selectable = false;
          if (item.children) {
            formatChildren(child);
          }
        });
      }

      // 添加不可选
      function formatTreeData(tree) {
        tree.map((item) => {
          if (item.children) {
            formatTreeData(item.children);
          }
          if (item.id === reactData.id) {
            item.selectable = false;
            if (item.children) {
              formatChildren(item.children);
            }
          } else {
            item.selectable = true;
          }
        });
      }

      function setReactDataId(allowRule) {
        allowRule.map((item) => {
          if (reactData.initRules.includes(item.id)) {
            reactData.rules.push(item.id);
          }
          if (item.children) {
            setReactDataId(item.children);
          }
        });
      }

      async function getRuleTree(id) {
        console.log(`id`, id);
        if (!id) {
          id = 1;
        }
        await getAllowRule({ id }).then((res) => {
          reactData.allowRule = res.tree as AllowRule[];
          reactData.rules = [];
          setReactDataId(reactData.allowRule);
        });
      }

      function confirm() {
        console.log('确定');
        const data = getFieldsValue();
        data.rules = [...reactData.rules];
        if (reactData.id) {
          data.id = reactData.id;
        }
        console.log(`pid`, data);
        console.log(`data`, data);
        const childerData = { closeModal, data };
        emit('saveData', childerData);
      }
      return {
        register,
        schemas,
        registerForm,
        replaceFields,
        model: modelRef,
        confirm,
        ...toRefs(popupData),
        ...toRefs(reactData),
      };
    },
  });
</script>
<style lang="less">
  .ant-form-item-label {
    text-align: center !important;
  }

  .tree-wrap {
    display: flex;
  }

  .tree-label {
    width: 20.6%;
    margin-top: 8px;
    margin-bottom: 1em;
    text-align: center;
  }

  @media (max-width: 639px) {
    .ant-form-item-label {
      line-height: 2.5715 !important;
      text-align: center !important;
    }

    .tree-label {
      width: 24%;
      margin-top: 8px;
      margin-bottom: 1em;
      text-align: center;
    }
  }
</style>
