import SaveForm from '@/components/save-form'
import Pagination from '@/components/pagination'
import {
  NButton,
  NDataTable,
  NFormItem,
  NInput,
  NModal,
  NSelect,
  NSpace,
  NTag,
  useDialog,
  useMessage
} from 'naive-ui'
import { defineComponent, onMounted, reactive, ref } from 'vue'
import { resetPassword, sysEmployeePage, sysEmployeeRemove, sysEmployeeStatus } from '../api'
import EmployeeOperation from './employee-operation'
import { filterEmployee } from '@/utils/filters'
import { employeeArray } from '@/utils/searchArray'
import { useUserStore } from '@/store/modules/user'
import { TABS_ROUTES } from '@/store/mutation-types'
import { useRoute, useRouter } from 'vue-router'

export default defineComponent({
  name: 'subsidy-list',
  setup() {
    const router = useRouter()
    const route = useRoute()
    const userStore = useUserStore()
    const state = reactive({
      loading: false,
      pagination: {
        page: 1,
        rows: 10,
        pageTotal: 0
      },
      searchForm: {
        keyword: null,
        status: null
      },
      dataList: [] as any,
      visiableEmployee: false,
      employeeOperation: 'add',
      employeeData: {} as any
    })
    const dialog = useDialog()
    const message = useMessage()

    const columns = () => {
      return [
        {
          title: '编号',
          key: 'id'
        },
        {
          title: '姓名',
          key: 'nickname',
          width: '120px'
        },
        {
          title: '手机号',
          key: 'phone'
        },
        {
          title: '角色',
          key: 'roleList',
          // ellipsis: {
          //   tooltip: true
          // },
          width: '300px',
          render(row: any) {
            return (
              <NSpace>
                {row.roleList &&
                  row.roleList.map((role: any) => <NTag type="info">{role.roleName}</NTag>)}
              </NSpace>
            )
          }
        },
        {
          title: '岗位',
          key: 'positionList',
          render(row: any) {
            return (
              <NSpace>
                {row.positionList &&
                  row.positionList.map((role: any) => <NTag type="info">{role.roleName}</NTag>)}
              </NSpace>
            )
          }
        },
        {
          title: '状态',
          key: 'status',
          render(row: any) {
            return filterEmployee(row.status)
          }
        },
        {
          title: '操作',
          key: 'operation',
          render(row: any) {
            return (
              <NSpace>
                <NButton
                  type="primary"
                  size="small"
                  text
                  v-auth="sysEmployee/update1674715360078639106"
                  onClick={() => {
                    state.visiableEmployee = true
                    state.employeeOperation = 'edit'
                    state.employeeData = row
                  }}
                >
                  修改
                </NButton>
                <NButton
                  type="primary"
                  size="small"
                  text
                  v-auth="user/resetPassword1674715612475076610"
                  onClick={() => onResetPassword(row)}
                >
                  重置密码
                </NButton>
                {row.status !== 'CANCEL' && (
                  <NButton
                    type="primary"
                    size="small"
                    text
                    onClick={() => onChangeStatus(row)}
                    v-auth="sysEmployee/status1674715744645984257"
                  >
                    {row.status === 'LOCKED' ? '解冻' : '冻结'}
                  </NButton>
                )}
              </NSpace>
            )
          }
        }
      ]
    }

    // 重置密码
    const onResetPassword = (row: any): void => {
      dialog.warning({
        title: '警告',
        content: `重置"${row.nickname}"的密码，是否继续？`,
        positiveText: '确定',
        negativeText: '取消',
        onPositiveClick: async () => {
          try {
            await resetPassword({
              userId: row.id,
              password: 'mecmp' + row.phone.substr(7),
              clientType: row.clientType
            })
            message.success('重置成功')
          } catch {}
        }
      })
    }

    const onChangeStatus = (row: any) => {
      const statuStr = row.status === 'LOCKED' ? '解冻' : '冻结'
      dialog.warning({
        title: '警告',
        content: `是否${statuStr}"${row.nickname}"？`,
        positiveText: '确定',
        negativeText: '取消',
        onPositiveClick: async () => {
          try {
            await sysEmployeeStatus({ id: row.id })
            getList()
            message.success(statuStr + '成功')

            if (row.status !== 'LOCKED') {
              const userInfo: any = userStore.getUserInfo || {}

              if (userInfo.phone === row.phone) {
                userStore.logout().then(() => {
                  // 移除标签页
                  localStorage.removeItem(TABS_ROUTES)
                  router
                    .replace({
                      name: 'Login',
                      query: {
                        redirect: route.fullPath
                      }
                    })
                    .finally(() => location.reload())
                })
              }
            }
          } catch {}
        }
      })
    }

    const getList = async () => {
      try {
        state.loading = true
        const { data } = await sysEmployeePage({ ...state.pagination, ...state.searchForm })
        state.loading = false
        state.pagination.pageTotal = Number(data.total)
        state.dataList = data.rows || []
      } catch {
        state.loading = false
      }
    }

    const saveForm = ref()
    const onSubmit = () => {
      state.pagination.page = 1
      getList()
    }

    const onSearch = () => {
      saveForm.value?.submit()
    }
    const onBtnReset = () => {
      saveForm.value?.reset()
    }

    onMounted(() => {
      getList()
    })
    return () => (
      <div class="system-menu-container">
        {/* <h2>员工管理</h2> */}
        <SaveForm
          ref={saveForm}
          model={state.searchForm}
          onSubmit={onSubmit}
          saveKey="EmployeeManage"
          onSetModel={(val: any) => (state.searchForm = val)}
        >
          <NFormItem label="关键字" path="search">
            <NInput
              v-model:value={state.searchForm.keyword}
              placeholder="员工编号/姓名/手机号"
              clearable
            />
          </NFormItem>
          <NFormItem label="状态" path="status">
            <NSelect
              v-model:value={state.searchForm.status}
              placeholder="请选择状态"
              options={employeeArray}
              clearable
            />
          </NFormItem>
          <NFormItem>
            <NSpace>
              <NButton type="primary" onClick={onSearch}>
                搜索
              </NButton>
              <NButton type="default" onClick={onBtnReset}>
                重置
              </NButton>
            </NSpace>
          </NFormItem>
        </SaveForm>

        <div class={['section-container']}>
          <NSpace style={{ paddingBottom: '12px' }}>
            <NButton
              type="primary"
              v-auth="sysEmployee/save1674715276184170497"
              onClick={() => {
                state.visiableEmployee = true
                state.employeeOperation = 'add'
                state.employeeData = {}
              }}
            >
              添加员工
            </NButton>
          </NSpace>

          <NDataTable
            loading={state.loading}
            columns={columns()}
            data={state.dataList}
          ></NDataTable>
          <Pagination
            saveKey="EmployeeManage"
            v-model:page={state.pagination.page}
            v-model:pageSize={state.pagination.rows}
            v-model:pageTotal={state.pagination.pageTotal}
            onList={getList}
            sync
          ></Pagination>
        </div>
        <NModal
          v-model:show={state.visiableEmployee}
          preset="dialog"
          showIcon={false}
          title={state.employeeOperation === 'add' ? '新增员工' : '修改员工'}
          style={{ width: '700px' }}
        >
          <EmployeeOperation
            type={state.employeeOperation}
            data={state.employeeData}
            onClose={() => (state.visiableEmployee = false)}
            onGetList={getList}
          />
        </NModal>
      </div>
    )
  }
})
