<script lang="ts" setup>
import type { BasicForm, ICRUD } from '@/types/form'
import mapi from '@/api/menu/menu'
import api from '@/api/menu/menuPermission'
import cindApi from '@/api/menu/menuPermissionCondition'

const props = defineProps({
  id: {
    type: String,
    default: ''
  },
  classPath: {
    type: String,
    default: ''
  }
})
const nameList = ref<any>([])

const selectArray = ref<any>({
  matchLogicArray: [
    { label: 'and', value: 'and' },
    { label: 'or', value: 'or' }
  ],
  conditionSymbolArray: [
    { label: 'and', value: 'and' },
    { label: 'or', value: 'or' }
  ],
  conditionArray: [],
  condition: {}
})

const conditionJson = ref<any>([])

const itemTableRef = ref<any>(null)

const LEFTCRUD: ICRUD = {
  create(data: any) {
    data.conditionJson = JSON.stringify(conditionJson.value)
    data.menuId = props.id
    return api.addMenuPermission(data)
  },
  update(data: any) {
    data.conditionJson = JSON.stringify(conditionJson.value)
    data.menuId = props.id
    return api.updateMenuPermission(data)
  },
  getList(data: any) {
    data.menuId = props.id
    return api.listMenuPermission(data).then((res: any) => {
      cindApi.allListMenuPermissionCondition({ menuId: props.id }).then((res: any) => {
        if (res.code == 200) {
          selectArray.value.conditionArray = res.data

          let conditionArray = selectArray.value.conditionArray
          for (let i = 0; i < conditionArray.length; i++) {
            selectArray.value.condition[conditionArray[i].id] = JSON.parse(conditionArray[i].conditionSymbol)
          }
        }
      })
      return {
        list: res.data.records,
        total: res.data.total
      }
    })
  },
  delete(data: any) {
    return api.delMenuPermission({
      ids: data.id
    })
  },
  getRecord(data: any) {
    return api.getMenuPermission(data.id).then(res => {
      conditionJson.value = JSON.parse(res.data.conditionJson)
      return res
    })
  }
}

const logtFormConfig = reactive<BasicForm>({
  span: 12,
  formItems: [
    {
      label: '方案名称',
      value: '',
      name: 'name',
      type: 'input',
      rules: [{ required: true, message: '方案名称不能为空', trigger: 'blur' }],
      search: true
    },
    {
      label: '方案编码',
      value: '',
      name: 'code',
      type: 'input',
      rules: [{ required: true, message: '方案编码不能为空', trigger: 'blur' }],
      search: true
    },
    {
      label: '规则实体类',
      value: '',
      name: 'ruleEntity',
      type: 'input',
      rules: [{ required: true, message: '规则实体类不能为空', trigger: 'blur' }],
      search: false
    },
    {
      label: '匹配逻辑',
      value: '',
      name: 'matchLogic',
      rules: [{ required: true, message: '匹配逻辑不能为空', trigger: 'blur' }],
      type: 'select',
      options: [
        { label: 'and', value: '0' },
        { label: 'or', value: '1' }
      ]
    },
    {
      span: 24,
      label: '过滤条件',
      value: '',
      name: '',
      type: 'custom',
      slots: [
        {
          name: 'default',
          alias: 'condition'
        }
      ]
    }
  ]
})

const addConditionGroup = () => {
  conditionJson.value.push({
    logic: '',
    groups: []
  })
}

const addCondition = (index: any) => {
  conditionJson.value[index].groups.push({})
}
const delCondition = (gropindex: any, index: any) => {
  conditionJson.value[gropindex].groups.splice(index, 1)
}
const delConditionGroup = (index: any) => {
  conditionJson.value.splice(index, 1)
}

const activeName = ref<any>(0)

const selectData = ref<any>({
  permissionJson: {
    array: {}
  },
  conditionTextArray: [
    { value: 'input', label: '任意文本' },
    { value: '@userId', label: '当前用户' },
    { value: '@organizeId', label: '当前组织' }
  ],
  fieldRuleArray: [
    { value: 0, label: '主表规则' },
    { value: 1, label: '副表规则' },
    { value: 2, label: '子表规则' }
  ],
  conditionSymbolArray: [
    { value: '>=', label: '大于等于' },
    { value: '>', label: '大于' },
    { value: '==', label: '等于' },
    { value: '<=', label: '小于等于' },
    { value: '<', label: '小于' },
    { value: '<>', label: '不等于' },
    { value: 'between', label: '介于' },
    { value: 'null', label: '为空' },
    { value: 'notNull', label: '不为空' },
    { value: 'in', label: '包含任意一个' },
    { value: 'notIn', label: '不包含任意一个' },
    { value: 'like', label: '包含' },
    { value: 'notLike', label: '不包含' },
    { value: 'and', label: '并且' },
    { value: 'or', label: '或者' },
  ]
})

const rightLogtFormConfig = reactive<BasicForm>({
  span: 12,
  formItems: [
    {
      label: '字段名称',
      value: '',
      name: 'name',
      type: 'select',
      request: () => {
        return mapi.getPermissionParam(props.classPath).then(res => {
          nameList.value = res.data
          return res.data
        })
      },
      props: {
        clearable: true,
        filterable: true,
        'default-first-option': true,
        "allow-create": true
      },
      events: {
        change: (el: any) => {
          const field = nameList.value.find((item: any) => item.value == el)?.value
          const entity = nameList.value.find((item: any) => item.value == el)?.table
          const name = nameList.value.find((item: any) => item.value == el)?.type
          nextTick(() => {
            itemTableRef.value.formData.code = field
            itemTableRef.value.formData.bindTable = entity
            itemTableRef.value.formData.type = name
          })
        },
      },
      rules: [{ required: true, message: '字段名称不能为空', trigger: 'blur' }],
      search: true
    },
    {
      label: '编码',
      value: '',
      name: 'code',
      type: 'input',
      rules: [{ required: true, message: '编码不能为空', trigger: 'blur' }],
      search: true
    },
    {
      label: '表别名',
      value: '',
      name: 'bindTable',
      rules: [{ required: true, message: '表别名不能为空', trigger: 'blur' }],
      type: 'input'
    },
    {
      label: '字段类型',
      value: '',
      name: 'type',
      rules: [{ required: true, message: '字段类型不能为空', trigger: 'blur' }],
      type: 'select',
      options: [
        {
          label: 'string',
          value: 'string'
        },
        {
          label: 'int',
          value: 'int'
        },
        {
          label: 'double',
          value: 'double'
        },
        {
          label: 'varchar',
          value: 'varchar'
        },
        {
          label: 'text',
          value: 'text'
        },
        {
          label: 'bigint',
          value: 'bigint'
        },
      ]
    },
    {
      label: '条件内容',
      value: '',
      name: 'conditionText',
      rules: [{ required: true, message: '条件内容不能为空', trigger: 'blur' }],
      type: 'select',
      options: [
        {
          label: '当前用户',
          value: '@userId'
        },
        {
          label: '当前用户及下属',
          value: '@userAraSubordinates'
        },
        {
          label: '当前组织',
          value: '@organizeId'
        },
        {
          label: '当前组织及子组织',
          value: '@organizationAndSuborganization'
        },
        {
          label: '当前分管组织',
          value: '@branchManageOrganize'
        },
        {
          label: '当分管组织及子组织',
          value: "@branchManageOrganizeAndSub",
        },
        {
          label: '当前部门的上级部门',
          value: "@parentOrganize",
        },
        {
          label: '当前部门的上级部门的子部门',
          value: '@parentOrganizeUnder'
        },
        {
          label: '任意文本',
          value: 'input'
        },
      ]
    },
    {
      label: '条件符号',
      value: '',
      name: 'conditionSymbol',
      props: {
        multiple: true
      },
      rules: [{ required: true, message: '条件符号不能为空', trigger: 'blur' }],
      type: 'select',
      options: selectData.value.conditionSymbolArray
    }
  ]
})

const RIGHTCRUD: ICRUD = {
  create(data: any) {
    let conditionSymbol = data.conditionSymbol
    let conditionSymbolArray = selectData.value.conditionSymbolArray
    let conditionSymbolName = ''
    for (let i = 0; i < conditionSymbol.length; i++) {
      for (let j = 0; i < conditionSymbolArray.length; j++) {
        if (conditionSymbol[i] === conditionSymbolArray[j].value) {
          conditionSymbolName += conditionSymbolArray[j].label
          break
        }
      }
      if (i != conditionSymbol.length - 1) {
        conditionSymbolName += ','
      }
    }
    data.conditionSymbol = JSON.stringify(conditionSymbol)
    data.conditionSymbolName = conditionSymbolName
    data.menuId = props.id
    return cindApi.addMenuPermissionCondition(data)
  },
  update(data: any) {
    let conditionSymbol = data.conditionSymbol
    let conditionSymbolArray = selectData.value.conditionSymbolArray
    let conditionSymbolName = ''
    for (let i = 0; i < conditionSymbol.length; i++) {
      for (let j = 0; i < conditionSymbolArray.length; j++) {
        if (conditionSymbol[i] === conditionSymbolArray[j].value) {
          conditionSymbolName += conditionSymbolArray[j].label
          break
        }
      }
      if (i != conditionSymbol.length - 1) {
        conditionSymbolName += ','
      }
    }
    data.conditionSymbol = JSON.stringify(conditionSymbol)
    data.conditionSymbolName = conditionSymbolName
    data.menuId = props.id
    return cindApi.updateMenuPermissionCondition(data)
  },
  getList(data: any) {
    data.menuId = props.id
    return cindApi.listMenuPermissionCondition(data).then((res: any) => {
      return {
        list: res.data.records,
        total: res.data.total
      }
    })
  },
  delete(data: any) {
    return cindApi.delMenuPermissionCondition(data.id)
  },
  getRecord(data: any) {
    return cindApi.getMenuPermissionCondition(data.id).then((res: any) => {
      res.data.conditionSymbol = JSON.parse(res.data.conditionSymbol)
      return {
        data: res.data
      }
    })
  }
}

const changeCondition = (res: any, groupIndex: any, index: any) => {
  selectArray.value.conditionArray.forEach((element: any) => {
    if (element.id == res) {
      console.log('表单字段', itemTableRef.value.formData)
      const valueObject = ref<any>({
        value: element.conditionText,
        field: element.code,
        type: itemTableRef.value.formData.name,
        fieldRule: '',
        bindTable: element.bindTable,
        condition: element.code,
        conditionText: element.conditionText,
        childTableKey: '',
        conditionId: element.id,
      })


      // element.field = element.conditionText,
      // element.op = element.symbol,
      // element.type = itemTableRef.value.formData.name,
      // element.value = element.conditionText,
      // element.fieldRule = '',
      // element.bindTable = '',
      // element.condition = res,
      // element.childTableKey = ''

      conditionJson.value[groupIndex].groups[index] = valueObject.value
      conditionJson.value[groupIndex].groups[index].conditionType = element.conditionText
      console.log('element', element)
      console.log('选完后的数据', conditionJson.value[groupIndex].groups[index])
    }
  });
}

const handleCreate = () => {
  conditionJson.value = []
}



const programmeList = ref<any>([])
const queryList = () => {
  api.findCommonSolutionsList({
    sysData: 1
  }).then(res => {
    programmeList.value = res.data
  })
}

const setProgramme = (e: any) => {
  api.saveByCommonSolutions({
    menuId: props.id,
    commonSolutionsId: e.id
  }).then((res: any) => {
    if (res.code == 200) {
      itemTableRef.value.refresh()
    }
  })
}


const dialogVisible = ref(false)

const formData = ref<any>({})
const orgFormConfig = reactive<BasicForm>({
  span: 24,
  formItems: [
    {
      label: '数据连接',
      value: 'class',
      name: 'type',
      props: {
        disabled: true
      },
      type: 'select',
      options: [
        {
          label: '实体类',
          value: 'class'
        }]
    },
    {
      label: '数据选择',
      value: '',
      name: 'name',
      type: 'input',
    },
  ]
})



const dataLink = () => {

  api.getMenuPermissionData({ menuId: props.id }).then(res => {
  if(res.data == null){
    formData.value = {
      type:'class'
    }
  }else{
    formData.value = res.data

  }
  })
  dialogVisible.value = true

}

const create = (data: any) => {
  data.menuId = props.id
  return api.saveMenuPermissionData(data).then(() => {
    dialogVisible.value = false
  })
}


const handleEdit = (row: any) => {
  itemTableRef.value.handleUpdate(row)
}


</script>

<template>
  <div>
    <el-button-group class="mb-3">
    <el-button @click="activeName = 0" :type="activeName == 0 ? 'primary' : 'info'">数据权限方案</el-button>
    <el-button @click="activeName = 1" :type="activeName == 0 ? 'info' : 'primary'">数据权限字段</el-button>
  </el-button-group>

  <div v-if="activeName == 0">
    <el-alert title="维护数据权限方案，通过配置的数据权限字段，自定义数据的筛选" type="warning" :closable="false" />
    <el-alert title="快捷方案为系统提供的默认筛选方案" type="warning" :closable="false" />
    <pro-table :crud="LEFTCRUD" :tree-config="{}" ref="itemTableRef" height="70vh"
      :tableConfig="{ operateWidth: 230, showEdit: false, }" 
      :formConfig="logtFormConfig" :selection="false" @click-create="handleCreate">
      <template #toolbar="toolbar">
        <el-dropdown trigger="click">
          <el-button type="primary" class="ml-3" @click="queryList">
            快捷方案<el-icon class="el-icon--right"><arrow-down /></el-icon>
          </el-button>
          <template #dropdown>
            <el-dropdown-menu v-for="(item, index) in programmeList">
              <el-dropdown-item @click="setProgramme(item)">
                {{ item.name }}
              </el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
      </template>
      <template #condition>
        <ElCard class="w-full mb-10px" v-for="(groupItem, groupIndex) in conditionJson" shadow="never">
          <ElRow>
            <div class="adddel">
              <div class="w-300px mr-3">
                <el-select v-model="groupItem.logic" sty>
                  <el-option v-for="item in selectArray.conditionSymbolArray" :key="item.value" :label="item.label"
                    :value="item.value" />
                </el-select>
              </div>

              <ElButton @click="addCondition(groupIndex)" type="primary">添加字段</ElButton>
              <ElButton @click="delConditionGroup(groupIndex)" type="danger">移除字段组</ElButton>
            </div>

            <ElCard v-for="(item, index) in groupItem.groups" class="w-full mb-10px" shadow="never">
              <ElRow :gutter="24">
                <ElCol :span="5">
                  <el-select v-model="conditionJson[groupIndex].groups[index].conditionId"
                    @change="(res: any) => changeCondition(res, groupIndex, index)">
                    <el-option v-for="item in selectArray.conditionArray" :key="item.id" :label="item.name"
                      :value="item.id" />
                  </el-select>
                </ElCol>
                <ElCol :span="5">
                  <el-select v-model="conditionJson[groupIndex].groups[index].op">
                    <el-option v-for="itm in selectArray.condition[item.conditionId]" :key="itm" :label="itm"
                      :value="itm" />
                  </el-select>
                </ElCol>
                <ElCol :span="5">
                  <ElInput v-model="conditionJson[groupIndex].groups[index].value"
                    :disabled="conditionJson[groupIndex].groups[index].conditionType != 'input'" placeholder="请输入数据权限方案名称"
                    show-word-limit minlength="1" maxlength="100" />
                </ElCol>
                <ElCol :span="4">
                  <ElButton @click="delCondition(groupIndex, index)" class="border-style-dashed" type="danger">移除
                  </ElButton>
                </ElCol>
              </ElRow>
            </ElCard>
          </ElRow>
        </ElCard>
        <ElButton @click="addConditionGroup()" class="mt-10px w-25% border-style-dashed" type="primary">添加字段组</ElButton>
      </template>

      <vxe-column field="name" title="方案名称" tree-node></vxe-column>
      <vxe-column field="code" title="方案编码"></vxe-column>
      <!-- <vxe-column field="conditionJson" title="多分组多条件json" width="150"></vxe-column> -->
      <vxe-column field="matchLogic" title="匹配逻辑">
        <template #default="{ row }">
          <div>{{ row.matchLogic == '0' ? 'and' : 'or' }}</div>
        </template>
      </vxe-column>

      <template #operateAfter="{ row }">
        <el-button type="primary" plain size="small" v-if="row.source == 0" @click="handleEdit(row)"> 编辑 </el-button>
      </template>
    </pro-table>
  </div>
  <div v-else>
    <el-alert title="维护数据权限方案要使用到的字段信息" type="warning" :closable="false" />
    <el-alert title="数据连接设置要进行数据过滤的的实体类名(不含包名,例如：TenantQueryVO),将对findList和findAllList进行数据过滤。" type="warning"
      :closable="false" />
    <pro-table :crud="RIGHTCRUD" :tree-config="{}" height="70vh" ref="itemTableRef" :tableConfig="{ operateWidth: 150 }"
       :formConfig="rightLogtFormConfig" :selection="false">
      <template #toolbar="toolbar">
        <el-button type="primary" @click="dataLink">数据连接</el-button>
      </template>
      <vxe-column field="name" title="字段名称" tree-node></vxe-column>
      <vxe-column field="code" title="编码"></vxe-column>
      <vxe-column field="bindTable" title="表别名"></vxe-column>
      <vxe-column field="type" title="字段类型"></vxe-column>
      <vxe-column field="conditionSymbolName" title="条件符号名称"></vxe-column>
    </pro-table>
    <dialog-form v-model="dialogVisible" :formConfig="orgFormConfig" :formData="formData" :create="create"
      :update="create" v-if="dialogVisible" />
  </div>
  </div>
  
</template>

<style lang="scss" scoped>
.adddel {
  display: flex;
  justify-content: space-between;
  align-items: center;
  // margin-left: 2%;
}
@media only screen and (min-width: 1200px) {
    :deep(.el-col-lg-6) {
        flex: 0 0 50% !important;
        max-width: 50% !important;
       
    }}
</style>
