<template>
  <fvSearchForm :searchConfig="searchConfig" @search="search" style="margin-left: 16px"></fvSearchForm>
  <fvTable ref="tableIns" :tableConfig="tableConfig" @headBtnClick="headBtnClick"></fvTable>
</template>

<script setup lang="jsx">
import fvSelect from '@/fvcomponents/fvSelect/index.vue'
import Tag from '@/components/Tag.vue'
import { ElMessageBox, ElNotification } from 'element-plus';
import { deleteRole } from "@/api/role/role";
import { useAuthStore } from '@/stores/userstore.js'
import {getSubCompOpt} from "@/api/user/user";

const authStore = useAuthStore()
const router = useRouter()

const shortcuts = [
  {
    text: '上周',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
      return [start, end]
    },
  },
  {
    text: '上月',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
      return [start, end]
    },
  },
  {
    text: '三月前',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
      return [start, end]
    },
  },
]

const searchConfig = ref([
  {
    label: '公司名称',
    prop: 'subCompanyId',
    component: 'el-tree-select',
    props: {
      placeholder: '请选择公司名称',
      clearable: true,
      data: [],
      filterable: true,
      checkStrictly: true,
      remote: true
    },
  },
  {
    label: '角色名称',
    prop: 'roleName',
    component: 'el-input',
    props: {
      placeholder: '请输入角色名称',
      clearable: true
    }
  },
  {
    label: '权限字符',
    prop: 'roleKey',
    component: 'el-input',
    props: {
      placeholder: '请输入权限字符',
      clearable: true
    }
  },
  {
    label: '状态',
    prop: 'state',
    component: shallowRef(fvSelect),
    props: {
      placeholder: '请选择状态',
      clearable: true,
      cacheKey: 'normal_disable',
      remote: true,
      filterable: true
    }
  },
  // {
  //   label: '登录时间',
  //   prop: 'dateValue',
  //   component: 'el-date-picker',
  //   props: {
  //     placeholder: '请选择',
  //     clearable: true,
  //     type: 'datetimerange',
  //     startPlaceholder: '开始日期',
  //     endPlaceholder: '结束日期',
  //     valueFormat: 'YYYY-MM-DD HH:mm:ss',
  //     shortcuts: shortcuts
  //   }
  // },
])

const tableIns = ref()

const auths = {
  edit: ['admin:role:edit'],
  del: ['admin:role:del'],
  add: ['admin:role:add'],
}

const tableConfig = reactive({
  columns: [
    {
      prop: 'index',
      type: 'index',
      label: '序号',
      align: 'center',
      width:85
    },
    {
      prop: 'roleName',
      label: '角色名称',
      align: 'center'
    },
    {
      prop: 'roleKey',
      label: '角色权限',
      align: 'center'
    },
    {
      prop: 'companyName',
      label: '公司名称',
      align: 'center'
    },
    {
      prop: 'template',
      label: '是否为模版角色',
      align: 'center',
      width:150,
      showOverflowTooltip: false,
      currentRender: ({row, index}) => (<Tag dictType={'yes_no'} value={row.template ? '1' : '0'} />)
    },
    {
      prop: 'roleSort',
      label: '显示顺序',
      align: 'center',
      width:100,
    },
    {
      prop: 'state',
      label: '状态',
      showOverflowTooltip: false,
      align: 'center',
      width:100,
      currentRender: ({row, index}) => (<Tag dictType={'normal_disable'} value={row.state} />)
    },
    {
      prop: 'oper',
      label: '操作',
      align: 'center',
      fixed: 'right',
      width:150,
      showOverflowTooltip: false,
      currentRender: ({row, index}) => {
        let btn = [{label: '修改', auth: auths.edit, func: ()=>handleEdit(row) , type: 'primary'}]
        // btn.push(
        //   {
        //     label: '分配用户',
        //     auth: auths.edit,
        //     func: ()=>handleAssign(row),
        //     type: 'primary'
        //   }
        // )
        if(authStore.roles.includes('superAdmin')) {
          btn.push({label: '删除', auth: auths.del, func: ()=>handleDel(row) , type: 'danger'})
        } else if(!row.template) {
          btn.push({label: '删除', auth: auths.del, func: ()=>handleDel(row) , type: 'danger'})
        }
        return (
          <div>
            {
              btn.map(item=>(
                <el-button
                  type={item.type}
                  v-perm={item.auth}
                  onClick={()=>item.func()}
                  link
                  >
                  {item.label}
                </el-button>
              ))
            }
          </div>
        )
      },
    }
  ],
  api: '/admin/role',
  btns: [{name: '新增', key: 'add', auth: auths.add, color:"#DED0B2"}],
  params: {}
})

const search = (val) => {
  let obj = {...val}
  if(obj.dateValue) {
    obj.startTime = obj.dateValue[0]
    obj.endTime = obj.dateValue[1]
    delete obj.dateValue
  }
  tableConfig.params = obj
  tableIns.value.refresh()
}


const handleAdd = () => {
  router.push({
    name: 'Roleadd',
    query: {
      isAdd: 1
    }
  })
}

const handleEdit = (row) => {
  router.push({
    name: 'Roleedit',
    query: {
      id: row.roleId
    }
  })
}

const handleAssign = (row) => {

}

const handleDel = (row) => {
  // if (!(row.template && authStore.roles.includes('superAdmin'))) {
  //   ElNotification({
  //     title: '提示',
  //     message: '模版角色只能由超级管理员删除!',
  //     type: 'warning'
  //   })
  //   return
  // }

  ElMessageBox.confirm('确定删除该条数据吗?', '确定删除', {
    type: 'warning',
    confirmButtonText: '确定',
    cancelButtonText: '取消'
  }).then(async res => {
    const { code, msg } = await deleteRole(row.roleId)
    ElNotification({
      title: '删除',
      message: msg,
      type: code === 1000 ? 'success' : 'error'
    })
    tableIns.value.refresh()
  }).catch(()=>{})
}

const headBtnClick = (key) => {
  switch(key) {
    case 'add': handleAdd()
      break;
  }
}

const init = async () => {
  if(!authStore.roles.includes('superAdmin')) {
    searchConfig.value = searchConfig.value.slice(1)
  }
  searchConfig.value = searchConfig.value
  const res = await getSubCompOpt()
  searchConfig.value.find(item=>item.prop == 'subCompanyId').props.data = res.data
}
init()

</script>
<style scoped lang="scss">
:deep(.el-table__header) {
  .is-leaf:first-child {
    .cell {
      margin-left: -25px !important;
    }
  }
}

:deep(.el-table__body) {
  .el-table__cell:first-child {
    .cell {
      margin-left: -13px !important;
    }
  }
}
:deep(.el-col-5:nth-child(4).el-col-offset-1){
  margin-left: 35px !important;
}
</style>

