<template>
  <fvSearchForm ref="form" :searchConfig="searchConfig" @search="search" style="margin-left: 16px"></fvSearchForm>
  <fvTable ref="tableIns" :tableConfig="tableConfig" @headBtnClick="headBtnClick"></fvTable>
  <user-picker :multiple="true" ref="userPicker" title="请选择研发人员" v-model:value="userList" @ok="selected"/>
</template>

<script setup lang="jsx">
import Tag from '@/components/Tag.vue'
import fvSelect from '@/fvcomponents/fvSelect/index.vue'
import UserPicker from "@/views/workflow/process/common/UserPicker.vue";
import { useAuthStore } from '@/stores/userstore.js'
import { getDeptOpt, getSubCompOpt,bindAccount,getBindAccount } from '@/api/user/user.js';
import {ElMessageBox, ElNotification} from 'element-plus';

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

const searchConfig = ref([
  {
    label: '公司名称',
    prop: 'subCompanyId',
    component: 'el-tree-select',
    props: {
      placeholder: '请选择公司名称',
      clearable: true,
      data: [],
      filterable: true,
      checkStrictly: true,
      remote: true
    },
    on: {
      change: async (val) =>{
        const { data } = await getDeptOpt({subCompanyId: val})
        searchConfig.value.find(item=>item.prop == 'departmentId').props.data = data
      }
    }
  },
  {
    label: '部门名称',
    prop: 'departmentId',
    component: 'el-tree-select',
    props: {
      placeholder: '请选择部门名称',
      clearable: true,
      data: [],
      filterable: true,
      checkStrictly: true,
      remote: true
    }
  },
  {
    label: '用户名称',
    prop: 'nickName',
    component: 'el-input',
    props: {
      placeholder: '请输入用户名称',
      clearable: true
    }
  },
  {
    label: '用户账号',
    prop: 'userName',
    component: 'el-input',
    props: {
      placeholder: '请输入用户账号',
      clearable: true
    }
  },
  {
    label: '状态',
    prop: 'state',
    component: shallowRef(fvSelect),
    props: {
      placeholder: '请选择状态',
      cacheKey: 'normal_disable',
      clearable: true,
      remote: true,
      filterable:true
    }
  },
])

const tableIns = ref()
const currentId = ref('')
const userList = ref([])
const userPicker = ref()
const auths = {
  edit: ['admin:user:edit'],
  del: ['admin:user:del'],
  add: ['admin:user:add'],
  bindUser: ['admin:bind:account'],
}

const tableConfig = reactive({
  columns: [
    {
      prop: 'index',
      type: 'index',
      label: '序号',
      align: 'center',
      width:85
    },
    {
      prop: 'userName',
      label: '用户账号',
      align: 'center',
    },
    {
      prop: 'nickName',
      label: '用户名称',
      align: 'center',
    },
    {
      prop: 'subCompanyName',
      label: '公司名称',
      align: 'center',
    },
    {
      prop: 'jobActivityDesc',
      label: '岗位名称',
      align: 'center',
    },
    {
      prop: 'departmentName',
      label: '部门',
      align: 'center',
    },
    {
      prop: 'mobile',
      label: '手机号码',
      align: 'center',
    },
    {
      prop: 'accountType',
      label: '主子账号',
      align: 'center',
      width: 100,
      showOverflowTooltip: false,
      currentRender: ({row, index}) => (<Tag dictType={'account_type'} value={row.accountType} />)
    },
    {
      prop: 'state',
      label: '状态',
      width: 80,
      align: 'center',
      showOverflowTooltip: false,
      currentRender: ({row, index}) => (<Tag dictType={'normal_disable'} value={row.state} />)
    },
    {
      prop: 'createTime',
      label: '创建时间',
      align: 'center',
    },
    {
      prop: 'oper',
      label: '操作',
      fixed: 'right',
      width: 180,
      align: 'center',
      showOverflowTooltip: false,
      currentRender: ({row, index}) => {
        return (
          <div>
            <el-button type="primary" v-perm={auths.edit} link onClick={()=>handleEdit(row)}>编辑</el-button>
            {
              row.userType != 0 ?
              <el-button type="danger" v-perm={auths.del} link onClick={()=>handleDel(row)}>删除</el-button> :
              null
            }
            {
              row.accountType == 0 ?
              <el-button type="primary" v-perm={auths.bindUser} link onClick={()=>handleBindAccount(row)}>绑定账号</el-button> :
              null
            }
          </div>
        )
      }
    }
  ],
  api: '/admin/mosr/user',
  params: {},
  btns: [
    {name: '新增', color:"#DED0B2", auth: ['admin:user:add'], key: 'add'}
  ]
})

const init = async () => {
  // console.log(authStore.roles,'userinfo');
  if(!authStore.roles.includes('superAdmin')) {
    searchConfig.value = searchConfig.value.slice(1)
  }
  searchConfig.value = searchConfig.value
  const { data } = await getDeptOpt()
  searchConfig.value.find(item=>item.prop == 'departmentId').props.data = data
  const res = await getSubCompOpt()
  searchConfig.value.find(item=>item.prop == 'subCompanyId').props.data = res.data
  // console.log("🚀 ~ init ~ searchConfig.value:", searchConfig.value)
}

init()

const search = (val) => {
  tableConfig.params = {...val}
  tableIns.value.refresh()
}

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

const handleEdit = (row) => {
  router.push({
    name: 'Useredit',
    query: {
      id: row.userId,
      userType: row.userType
    }
  })
}

const handleDel = (row) => {
  ElMessageBox.confirm('确定删除该条数据吗?', '确定删除', {
    type: 'warning',
    confirmButtonText: '确定',
    cancelButtonText: '取消'
  }).then(async res => {
    // const { code } = await
  }).catch(()=>{})
}
const handleBindAccount=(row)=>{
  currentId.value = row.userId
  getBindAccount(row.userId).then(res=>{
    if(res.code != 1000){
      ElNotification({
        title: '提示',
        message: res.msg,
        type: 'error'
      })
    }else {
      userList.value = res.data
      nextTick(()=>{
        userPicker.value.showUserPicker()
      })
    }
  })
}
const selected = (select) => {
  let userInfoList = []
  for (let val of select) {
    let userInfo = {
      id: val.id,
      name: val.name
    }
    userInfoList.push(userInfo)
  }
  userList.value = userInfoList
  let ids=userList.value.map(item=>item.id)
  let params={
    id:currentId.value,
    ids:ids
  }
  bindAccount(params).then(res=>{
    ElNotification({
      title: '提示',
      message: res.msg,
      type: res.code === 1000 ? 'success' : 'error'
    })
  })
}
const headBtnClick = (key) => {
  switch(key) {
    case 'add': handleAdd()
      break;
  }
}
</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>
