<template>
  <fvSearchForm ref="form" :searchConfig="searchConfig" @search="search" style="margin-left: 16px"></fvSearchForm>
<!--  <fvTable ref="tableIns" :tableConfig="tableConfig" @headBtnClick="headBtnClick"></fvTable>-->
  <div class="table-header-btn">
    <el-button color="#DED0B2" @click="handleAdd" v-perm="['admin:user:add']" >新增</el-button>
  </div>
  <div  class="fv-table">
    <el-table
        :data="list"
        row-key="userId"
        :lazy="true"
        v-loading="loading"
        v-tabh
    >
      <el-table-column label="序号" type="index" align="center" width="80">
        <template #default="scope">
          {{(pageInfo.pageNum - 1) * pageInfo.pageSize + scope.$index + 1}}
        </template>
      </el-table-column>
<!--                <el-table-column prop="userId" label="用户编号" align="center"/>-->
      <el-table-column prop="userName" label="用户账号" align="center"/>
      <el-table-column prop="nickName" label="用户名称" align="center"/>
      <el-table-column prop="subCompanyName" label="公司名称" align="center"/>
      <el-table-column prop="jobActivityDesc" label="岗位名称" align="center"/>
      <el-table-column prop="departmentName" label="部门" align="center"/>
      <el-table-column prop="mobile" label="手机号码" align="center"/>
      <el-table-column prop="accountType" label="主次账号" align="center" width="100">
        <template #default="scope">
          <Tag dictType="account_type" :value="scope.row.accountType"/>
        </template>
      </el-table-column>
      <el-table-column prop="state" label="状态" align="center" width="80">
        <template #default="scope">
          <tag dict-type="normal_disable" :value="scope.row.state"/>
        </template>
      </el-table-column>
      <el-table-column prop="createTime" label="创建时间" align="center" width="180px"/>
      <el-table-column label="操作" align="center" width="180">
        <template #default="scope">
          <el-button type="primary"   v-perm="auths.edit"
                     @click="handleEdit(scope.row)"  link>编辑
          </el-button>
          <el-button type="primary"   v-perm="auths.agentSetting"
                     @click="handleAgentSetting(scope.row)"  link>设置代理
          </el-button>
          <el-button type="danger" v-if="scope.row.userType != 0"  v-perm="auths.del"
                     @click="handleDel(scope.row)"  link>删除
          </el-button>
          <el-button type="primary"  v-if="scope.row.accountType == 0"  v-perm="auths.bindUser"
                     @click="handleBindAccount(scope.row)"  link>绑定账号
          </el-button>
<!--          <popover-delete :name="scope.row.userName" :type="'用户'"-->
<!--                          @delete="handleDelete(scope.row.userId)"/>-->
        </template>
      </el-table-column>
    </el-table>
  </div>
  <paging :current-page="pageInfo.pageNum" :page-size="pageInfo.pageSize" :page-sizes="[10, 20, 30, 40,50]"
          :total="total" @changeSize="handleSizeChange" @goPage="handleCurrentChange"/>
  <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,getMosrUserList} from '@/api/user/user.js';
import {ElMessageBox, ElNotification} from 'element-plus';

import Paging from "@/components/pagination/index.vue";
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 pageInfo = reactive({
  pageNum: 1,
  pageSize: 10
});
const list = ref([]);
const tableIns = ref()
const total = ref()
const loading = ref(false)
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'],
  agentSetting: ['admin:user:agentSetting'],
}

const tableConfig = reactive({
  columns: [
    {
      prop: 'index',
      type: 'index',
      label: '序号',
      align: 'center',
      width: 85,
      index: index => {
        return (tableIns.value.getQuery().pageNum - 1) * tableIns.value.getQuery().pageSize + index + 1
      }
    },
    {
      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>
              <el-button type="primary" v-perm={auths.agentSetting} link onClick={() => handleAgentSetting(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 search = (val) => {
  tableConfig.params = {...val}
  // tableIns.value.refresh()
  getList()
}

//切换每页显示条数
const handleSizeChange = (val) => {
  pageInfo.pageSize = val;
  getList();
};

//点击页码进行分页功能
const handleCurrentChange = (val) => {
  pageInfo.pageNum = val;
  getList();
};
//获取用户数据
const getList = async () => {
  let params = {
    ...tableConfig.params,
    ...pageInfo
  };
  loading.value = true
  getMosrUserList(params).then(res => {

    if (res.code === 1000) {
      list.value = res.data.rows;
      total.value = res.data.total;
      loading.value = false;
    }else{
      ElNotification({
        title: '提示',
        message: res.msg,
        type:  'error'
      })
    }
  });
};
getList()
const handleAgentSetting = (row) => {
  router.push({
    name: 'AgentSetting',
    query: {
      userId: row.userId,
    }
  })
}
const init = async () => {
  // console.log(authStore.roles,'userinfo');
  if (!authStore.roles.includes('superAdmin')) {
    searchConfig.value = searchConfig.value.slice(1)
  }else{
    const res = await getSubCompOpt()
    searchConfig.value.find(item => item.prop == 'subCompanyId').props.data = res.data
  }
  const {data} = await getDeptOpt()
  searchConfig.value.find(item => item.prop == 'departmentId').props.data = data
  // searchConfig.value = searchConfig.value
  // const res = await getSubCompOpt()
  // searchConfig.value.find(item => item.prop == 'subCompanyId').props.data = res.data
}

init()

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: -20px !important;
    }
  }
}

:deep(.el-table__body) {
  .el-table__cell:first-child {
    .cell {
      margin-left: -10px !important;
    }
  }
}

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