<template>
  <BasicTable @register="registerTable">
    <template #toolbar>
      <div class="w-2/5 flex justify-end">
        <!-- <Search @search="value => handleSearch('search', value)" placeholder="项目名称/项目编号" /> -->
        <a-button @click="syncAccount" class="ml-3">同步计量账号</a-button>
        <a-button type="primary" v-if="hasPermission" @click="showModalFn" class="ml-3"
          ><PlusOutlined />新增账号</a-button
        >
      </div>
    </template>
  </BasicTable>
  <BasicModal @register="registerModal" @ok="submitModal">
    <BasicForm @register="registerForm" ref="formElRef">
      <template #role="{ model, field }">
        <!-- <span v-if="hasAdmin" class="text-red">已存在管理员</span> -->
        <span>
          <a-switch v-model:checked="model[field]" size="small" />
          <span>设为<Icon icon="clarity:administrator-solid" />管理员</span>
        </span>
        <!-- <a-radio-group v-else v-model:value="model[field]">
          <a-radio :value="1"></a-radio>
        </a-radio-group> -->
      </template>
    </BasicForm>
  </BasicModal>
</template>
<script lang="ts">
  import { computed, defineComponent, nextTick, PropType, ref, watch } from 'vue'
  import { BasicTable, useTable } from '/@/components/Table'
  import { BasicModal, useModal } from '/@/components/Modal'
  import { PlusOutlined } from '@ant-design/icons-vue'
  import { BasicForm, FormActionType, FormSchema, useForm } from '/@/components/Form/index'
  import { getTableColumns } from './tableData'
  import {
    getProjectAccount,
    addProjectAccount,
    saveProjectAccount,
    syncProjectAccountFromJL
  } from '/@/api/sys/project'
  import { propTypes } from '/@/utils/propTypes'
  import { Switch } from 'ant-design-vue'
  import { Icon } from '/@/components/Icon/index'
  import { AddOrUpdateProjectAccountParams, ProjectAccountItem } from '/@/api/sys/model/projectModel'
  import { useMessage } from '/@/hooks/web/useMessage'
  import { useUserStore } from '/@/store/modules/user'

  export default defineComponent({
    name: 'ProjectDetailAccount',
    components: {
      BasicTable,
      BasicModal,
      BasicForm,
      PlusOutlined,
      // ARadio: Radio,
      // ARadioGroup: Radio.Group,
      ASwitch: Switch,
      Icon
    },
    props: {
      id: {
        type: String as PropType<string>,
        default: null
      },
      activeId: {
        type: String as PropType<string>,
        default: '1'
      },
      hasPermission: propTypes.bool
    },
    setup(props) {
      const userStore = useUserStore()
      const gorupList = computed(() => userStore.getGroupList)
      if (!gorupList.value.length) {
        userStore.fetchGroupList()
      }
      const formElRef = ref<Nullable<FormActionType>>(null)
      const formType = ref(0) // 0 - 创建账号 1 - 更新账号
      const { createMessage } = useMessage()
      const [registerTable, { setTableData, reload }] = useTable({
        columns: getTableColumns((item: ProjectAccountItem) => showUpdateModalFn(item), props.hasPermission),
        showTableSetting: true,
        canResize: true
      })
      const fetchTableData = async (projectId: string) => {
        const data = await getProjectAccount({ projectId })
        setTableData(data)
      }
      watch(
        props,
        newProps => {
          if (newProps.activeId === '2') {
            fetchTableData(props.id)
          }
        },
        { immediate: true }
      )
      const [registerModal, { openModal, setModalProps }] = useModal()
      const schemas = computed<FormSchema[]>(() => [
        {
          field: 'accountGroup',
          component: 'Select',
          label: '账号组',
          required: true,
          componentProps: {
            options: gorupList.value
          }
        },
        {
          field: 'id',
          component: 'Input',
          label: '登录账号',
          show: false
        },
        {
          field: 'account',
          component: 'Input',
          label: '登录账号',
          required: true
        },
        {
          field: 'password',
          component: 'InputPassword',
          label: '登录密码',
          required: true
        },
        {
          field: 'name',
          component: 'Input',
          label: '姓名',
          required: true
        },
        {
          field: 'company',
          component: 'Input',
          label: '单位名称',
          required: true
        },
        {
          field: 'position',
          component: 'Input',
          label: '角色/职位',
          required: true
        },
        {
          field: 'mobile',
          component: 'Input',
          label: '手机'
        },
        {
          field: 'telephone',
          component: 'Input',
          label: '电话'
        },
        {
          field: 'boolAdmin',
          label: '特殊账号',
          component: 'Switch',
          slot: 'role'
        }
      ])
      const [registerForm, { removeSchemaByFiled, appendSchemaByField, updateSchema }] = useForm({
        labelWidth: 120,
        schemas,
        showActionButtonGroup: false
      })

      async function showModalFn() {
        formType.value = 0
        openModal()
        setModalProps({
          title: '新增账号',
          okText: '确认添加'
        })
        await nextTick()
        await updateSchema({
          field: 'account',
          componentProps: {
            disabled: false
          }
        })
        await removeSchemaByFiled('password')
        await appendSchemaByField(
          {
            field: 'password',
            component: 'InputPassword',
            label: '登录密码',
            required: true
          },
          'account'
        )
        await formElRef.value?.resetFields()
      }

      /**同步计量账号 */
      async function syncAccount() {
        await syncProjectAccountFromJL({ id: props.id })
        reload()
      }

      async function showUpdateModalFn(item: ProjectAccountItem) {
        formType.value = 1
        openModal()
        setModalProps({
          title: '更新账号',
          okText: '确认更新'
        })
        await nextTick()
        removeSchemaByFiled('password')
        formElRef.value?.setFieldsValue({ ...item })
        if (item.jlAuth) {
          formElRef.value?.updateSchema({
            field: 'account',
            component: 'Input',
            label: '登录账号',
            required: true,
            componentProps: {
              disabled: true
            }
          })
        }
      }

      function submitModal() {
        formElRef.value?.validate().then(async (values: any) => {
          try {
            if (formType.value === 0) {
              await createProjectAccount({ ...values, projectId: props.id })
            } else {
              await updateProjectAccount({ ...values, projectId: props.id })
            }
          } finally {
            openModal(false)
            createMessage.success(formType.value === 0 ? '新建账号成功' : '更新账号成功')
            await fetchTableData(props.id)
          }
        })
      }

      async function createProjectAccount(values: AddOrUpdateProjectAccountParams) {
        await addProjectAccount(values)
      }

      async function updateProjectAccount(values: AddOrUpdateProjectAccountParams) {
        await saveProjectAccount(values)
      }

      return { formElRef, registerTable, registerModal, registerForm, showModalFn, submitModal, syncAccount }
    }
  })
</script>
