<template>
  <BasicDrawer
    v-bind="$attrs"
    @register="registerDrawer"
    showFooter
    :title="getTitle"
    width="50%"
    @ok="handleSubmit"
  >
    <a-form
      ref="formRef"
      :model="formData"
      :rules="rules"
      :label-col="labelCol"
      :wrapper-col="wrapperCol"
    >
      <a-form-item ref="title" label="功能" name="code">
        <a-select
          v-model:value="formData.code"
          placeholder="请选择"
          :options="codeOptions"
          @change="codeChange"
        />
      </a-form-item>
      <a-form-item ref="title" label="名称" name="name">
        <a-input v-model:value="formData.name" />
      </a-form-item>
      <a-form-item ref="title" label="对象类型" name="objectType">
        <a-radio-group
          v-model:value="formData.objectType"
          name="radioGroup"
          @change="radioObjectChange"
        >
          <a-radio value="2">角色</a-radio>
          <a-radio value="1">用户</a-radio>
          <a-radio value="3">所有用户</a-radio>
        </a-radio-group>
      </a-form-item>
      <a-form-item ref="title" label="授权对象" name="objectId" v-if="formData.objectType != '3'">
        <a-select
          v-if="formData.objectType == '2'"
          v-model:value="formData.objectId"
          placeholder="请选择"
          :options="roleOptions"
        />
        <a-select
          v-if="formData.objectType == '1'"
          v-model:value="formData.objectId"
          show-search
          placeholder="请选择"
          :options="userOptions"
          :filter-option="filterOption"
        />
      </a-form-item>
      <div
        style="margin: 0 25px 0 60px"
        v-if="formData.formula.conditions && formData.formula.conditions.length > 0"
      >
        <div
          class="flex mb-2 ai-c jc-sb"
          v-for="(item, index) in formData.formula.conditions"
          :key="index"
        >
          <div><DragOutlined /></div>
          <div class="circlebox">{{ index + 1 }}</div>
          <div>
            <a-select
              style="width: 130px"
              v-model:value="item.f_FieldId"
              placeholder="请选择"
              :options="fieldOptions"
            />
          </div>
          <div>
            <a-select
              style="width: 110px"
              v-model:value="item.f_Symbol"
              placeholder="请选择"
              :options="symbolOptions"
            />
          </div>
          <div>
            <a-select
              style="width: 180px; margin: 0 5px"
              v-model:value="item.f_FieldValueType"
              placeholder="请选择"
              :options="fieldTypeOptions"
            />
          </div>
          <div class="flex-1 mr-2">
            <a-input v-model:value="item.f_FieldValue" placeholder="字段值" />
          </div>
          <a-button danger type="primary" size="small" shape="circle" @click="delRoleClick(index)">
            <MinusOutlined />
          </a-button>
        </div>
      </div>
      <a-form-item ref="title" label="" name="">
        <a-button type="link" size="small" style="margin-left: 60px" @click="addRoleClick"
          ><PlusCircleOutlined />添加过滤条件</a-button
        >
      </a-form-item>
      <a-form-item ref="title" label="公式" name="formula">
        <a-input v-model:value="formData.formula.formula">
          <template #addonAfter>
            <a-popover title="请按如下规则编辑条件组合">
              <template #content>
                <div class="fz-14">
                  <p class="color1">(1 and 2) or (3 and 4)</p>
                  <p>1.有and和or必须加括号</p>
                  <p class="color2">1 and 2 or 3 and 4</p>
                  <p>2.一个括号里不能同时出现and和or</p>
                  <p class="color2">(1 and 2 or 3 )and 4</p>
                  <p>3.不允许出现不存在的编号</p>
                  <p class="color2">1 and 2 and 3 and 4 and 5</p>
                  <p>4.括号都是成对出现的</p>
                  <p class="color2">(1 and 2 and 3 and 4</p>
                </div>
              </template>
              <QuestionOutlined />
            </a-popover>
          </template>
        </a-input>
      </a-form-item>
    </a-form>
  </BasicDrawer>
</template>
<script lang="ts" setup>
  import { ref, computed, unref, reactive, toRaw } from 'vue';
  import {
    QuestionOutlined,
    PlusCircleOutlined,
    DragOutlined,
    MinusOutlined,
  } from '@ant-design/icons-vue';

  import { BasicDrawer, useDrawerInner } from '@/components/Drawer';
  import { getRoleListByPage } from '@/api/demo/system';
  import { getAccountList } from '@/api/demo/system';
  import { fun_GetPageList } from '@/api/demo/formModule';
  import { addTableData, editTableData, getFieldListData } from '@/api/permission/data';
  import { useMessage } from '@/hooks/web/useMessage';

  const { createMessage } = useMessage();
  const emit = defineEmits(['success', 'register']);
  const filterOption = (input: string, option: any) => {
    return option.label.toLowerCase().indexOf(input.toLowerCase()) >= 0;
  };

  const isUpdate = ref(true);
  const labelCol = { span: 4 };
  const wrapperCol = { span: 19 };
  const formData: any = ref({
    code: '',
    codeName: '',
    name: '',
    objectId: '',
    objectName: '',
    objectType: '2',
    type: 2,
    formula: {
      formula: '',
      conditions: [],
    },
  });
  const formRef = ref();
  const codeOptions: any = ref([]);
  const roleOptions: any = ref([]);
  const userOptions: any = ref([]);
  const fieldOptions: any = ref([]);
  const symbolOptions: any = ref([
    { label: '等于', value: '1' },
    { label: '大于', value: '2' },
    { label: '大于等于', value: '3' },
    { label: '小于', value: '4' },
    { label: '小于等于', value: '5' },
    { label: '包含', value: '6' },
    { label: '包含于', value: '7' },
    { label: '不等于', value: '8' },
    { label: '不包含', value: '9' },
    { label: '不包含于', value: '10' },
  ]);
  const fieldTypeOptions: any = ref([
    { label: '文本(string)', value: '1' },
    { label: '登录者ID', value: '2' },
    { label: '登录者账号', value: '3' },
    { label: '登录者部门', value: '4' },
    { label: '登录者部门及下属部门', value: '5' },
    { label: '登录者岗位', value: '6' },
    { label: '登录者角色', value: '7' },
    { label: '文本（int）', value: '10' },
  ]);

  const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async (data) => {
    setDrawerProps({ confirmLoading: false });
    isUpdate.value = !!data?.isUpdate;
    getCodeListData(); //获取功能列表
    getRoleListData(); //获取角色列表
    getUserListData(); //获取用户
    if (unref(isUpdate)) {
      formData.value = data.record;
      formData.value.objectType = data.record.objectType.toString();
      formData.value.formula = JSON.parse(data.record.formula);
    } else {
      formData.value = {
        code: '',
        codeName: '',
        name: '',
        objectId: '',
        objectName: '',
        objectType: '2',
        type: 2,
        formula: {
          formula: '',
          conditions: [],
        },
      };
    }
  });
  const getTitle = computed(() =>
    !unref(isUpdate) ? '新增自定义功能数据权限条件' : '自定义功能数据权限条件',
  );

  function addRoleClick() {
    const obj: any = {
      f_FieldId: '',
      f_FieldValue: '',
      f_Symbol: '1',
    };
    formData.value.formula.conditions.push(obj);
  }
  function delRoleClick(e) {
    formData.value.formula.conditions.splice(e, 1);
  }
  function radioObjectChange() {
    formData.value.objectId = '';
  }
  function codeChange(e) {
    console.log('eeeee', e);
    codeOptions.value.forEach((item) => {
      if (item.value == e) {
        // fieldOptions.value = item.column;
        getFieldOptionsList(e);
        formData.value.formula.conditions = [];
      }
    });
  }
  function getCodeListData() {
    fun_GetPageList({ page: 1, limit: 9999999 }).then((res: Recordable) => {
      const arr: any = [];
      if (res.items) {
        res.items.forEach((item) => {
          arr.push({
            label: item.name,
            value: item.id,
            column: JSON.parse(item.scheme).table.columns,
          });
          if (formData.value.code == item.id) {
            getFieldOptionsList(item.id);
            // fieldOptions.value = JSON.parse(item.scheme).table.columns;
          }
        });
      }
      codeOptions.value = arr;
    });
  }
  function getFieldOptionsList(code: any) {
    const param = {
      code: code,
    };
    getFieldListData(param).then((res: Recordable) => {
      const arr = JSON.parse(res.scheme).formInfo.tabList;
      console.log('arr', arr);
      const newArr: any = [];
      arr.forEach((ele) => {
        ele.schemas.forEach((item) => {
          if (item.field) {
            newArr.push({
              label: item.label,
              value: item.field,
            });
          }
        });
      });
      console.log('newArr', newArr);
      fieldOptions.value = newArr;
    });
  }
  function getRoleListData() {
    getRoleListByPage().then((res: Recordable) => {
      const arr: any = [];
      if (res.items) {
        res.items.forEach((item) => {
          arr.push({
            label: item.name,
            value: item.id.toString(),
          });
        });
      }
      roleOptions.value = arr;
    });
  }
  function getUserListData() {
    getAccountList({ page: 1, limit: 999999 }).then((res: Recordable) => {
      const arr: any = [];
      if (res.items) {
        res.items.forEach((item) => {
          arr.push({
            label: item.name,
            value: item.id.toString(),
          });
        });
      }
      userOptions.value = arr;
    });
  }

  const rules = reactive({
    code: [{ required: true, message: '请选择功能', trigger: 'blur' }],
    name: [{ required: true, message: '请输入名称', trigger: 'blur' }],
    // objectId: [{ required: true, message: '请选择授权对象', trigger: 'blur' }],
  });

  async function handleSubmit() {
    try {
      console.log('formData', formData.value);
      formRef.value
        .validate()
        .then(() => {
          const params = formData.value;
          if (params.objectId) {
            if (formData.value.objectType == '1') {
              const objectObj = userOptions.value.filter((ele) => ele.value == params.objectId);
              console.log('objectObj', objectObj);
              params.objectName = objectObj[0].label;
            } else {
              const objectObj = roleOptions.value.filter((ele) => ele.value == params.objectId);
              console.log('objectObj', objectObj);
              params.objectName = objectObj[0].label;
            }
          } else {
            params.objectName = '所有用户';
          }

          const codeObj = codeOptions.value.filter((ele) => ele.value == params.code);
          params.codeName = codeObj[0].label;
          if (!unref(isUpdate)) {
            addTableData(params).then((res: any) => {
              closeDrawer();
              createMessage.success(res);
              emit('success');
            });
          } else {
            editTableData(params).then((res: any) => {
              closeDrawer();
              createMessage.success(res);
              emit('success');
            });
          }
        })
        .catch((error) => {
          console.log('error', error);
        });
    } finally {
    }
  }
</script>
<style>
  .color1 {
    color: #1bb99a;
  }
  .color2 {
    color: #ff3015;
  }
  .fz-14 {
    font-size: 14px;
  }
  .ai-c {
    align-items: center;
  }
  .jc-sb {
    justify-content: space-between;
  }
  .circlebox {
    width: 28px;
    height: 28px;
    line-height: 28px;
    text-align: center;
    border: 1px solid #d9d9d9;
    border-radius: 4px;
    margin: 0 5px;
  }
</style>
