<template>
  <PageWrapper>
    <BasicTable @register="registerTable">
      <template #toolbar>
        <div class="w-2/5 flex">
          <Search @search="value => handleSearch('search', value)" placeholder="项目名称/项目编号" />
          <a-button v-if="hasPermission([RoleEnum.ADMIN])" @click="showModalFn" class="ml-3"
            ><PlusOutlined />新增项目</a-button
          >
        </div>
      </template>
      <template #filterDropdown="{ setSelectedKeys, selectedKeys, confirm, clearFilters }">
        <div class="p-3">
          <a-select
            :options="options"
            placeholder="按办事处筛选"
            @select="value => setSelectedKeys([value])"
            allowclear
          />
        </div>
        <div class="pb-3 justify-center flex">
          <a-button size="small" @click="() => handleSearch('insideCategoryId', selectedKeys[0], confirm)" class="mr-3"
            >确定</a-button
          >
          <a-button size="small" @click="() => clearFilters()">重置</a-button>
        </div>
      </template>
    </BasicTable>
    <BasicModal @register="registerModal" @ok="submitModal">
      <BasicForm @register="registerForm" ref="formElRef" />
    </BasicModal>
  </PageWrapper>
</template>
<script lang="ts">
  import { computed, defineComponent, ref } from 'vue'
  import { BasicTable, useTable } from '/@/components/Table'
  import { BasicModal, useModal } from '/@/components/Modal'
  import { BasicForm, FormActionType, FormSchema, useForm } from '/@/components/Form/index'
  import { PlusOutlined } from '@ant-design/icons-vue'
  import { PageWrapper } from '/@/components/Page'
  import { RoleEnum } from '/@/enums/roleEnum'
  import { getProjectList } from '/@/api/sys/project'
  import { Input, Select } from 'ant-design-vue'
  import { getProjectTableColumns } from './tableData'
  import { useOfficeStore } from '/@/store/modules/office'
  import { ProjectListItem, ProjectListParams, ProjectUpdateOrCreateParams } from '/@/api/sys/model/projectModel'
  import { addProject } from '/@/api/sys/project'
  import { onMountedOrActivated } from '/@/hooks/core/onMountedOrActivated'
  import { useMessage } from '/@/hooks/web/useMessage'
  import { usePermission } from '/@/hooks/web/usePermission'

  export default defineComponent({
    name: 'Workbench',
    components: {
      PageWrapper,
      BasicTable,
      Search: Input.Search,
      ASelect: Select,
      BasicModal,
      BasicForm,
      PlusOutlined
    },
    setup() {
      const { hasPermission } = usePermission()
      const { createMessage } = useMessage()
      const formElRef = ref<Nullable<FormActionType>>(null)
      const officeStore = useOfficeStore()
      const options = computed(() => officeStore.getCategoryOptions)
      const staffOptions = computed(() => officeStore.getCategoriedStaff)
      const schemas = computed<FormSchema[]>(() => [
        {
          field: 'code',
          component: 'Input',
          label: '项目编号',
          required: true
        },
        {
          field: 'name',
          component: 'Input',
          label: '项目名称',
          required: true
        },
        {
          field: 'insideCategoryId',
          component: 'Select',
          componentProps: {
            options,
            showArrow: true
          },
          label: '所在办事处',
          required: true
        },
        {
          field: 'categoryId',
          component: 'Select',
          label: '销售负责人',
          componentProps: {
            options,
            showArrow: true,
            onChange: async (value: string) => {
              officeStore.getStaffWithCategoryIdAction({ categoryId: value })
              const formRef = formElRef.value
              formRef?.setFieldsValue({ staffId: '' })
            }
          },
          colProps: {
            span: 15
          },
          required: true
        },
        {
          field: 'staffId',
          component: 'Select',
          disabledLabelWidth: true,
          componentProps: {
            showArrow: true,
            options: staffOptions
          },
          label: '',
          colProps: {
            span: 8,
            offset: 1
          }
        },
        {
          field: 'staffPhone',
          component: 'Input',
          label: '负责人电话'
        },
        {
          field: 'staffQq',
          component: 'Input',
          label: '负责人QQ'
        },
        {
          field: 'staffTelephone',
          component: 'Input',
          label: '负责人座机'
        },
        {
          field: 'remark',
          label: '备注',
          component: 'InputTextArea'
        }
      ])
      async function checkOffice() {
        if (!officeStore.getOfficesAction.length) {
          await officeStore.getOfficesAction()
        }
      }
      const [registerTable, { setTableData, reload }] = useTable({
        canResize: true,
        title: '项目列表',
        rowKey: 'id',
        api: getProjectList,
        columns: getProjectTableColumns(),
        showTableSetting: true
      })

      const [registerModal, { openModal, setModalProps }] = useModal()
      const [registerForm] = useForm({
        labelWidth: 120,
        schemas,
        showActionButtonGroup: false
      })

      onMountedOrActivated(async () => {
        checkOffice()
      })

      async function handleSearch(key: keyof ProjectListParams, value: string, fn?: Fn) {
        if (fn) {
          fn()
        } else {
          const tableData = await getProjectList({ page: 1, pageSize: 10, [key]: value })
          setTableData<ProjectListItem>(tableData.items)
        }
      }
      async function showModalFn() {
        openModal()
        setModalProps({
          title: '新增项目',
          okText: '确认添加'
        })
      }

      function submitModal() {
        formElRef.value?.validate().then((values: ProjectUpdateOrCreateParams) => {
          createProject(values)
        })
      }

      async function createProject(values: ProjectUpdateOrCreateParams) {
        const newVals = { ...values }
        if (values.categoryId) {
          newVals.category = options.value.find(item => item.value === values.categoryId)?.label || ''
        }
        if (values.insideCategoryId) {
          newVals.insideCategory = options.value.find(item => item.value === values.insideCategoryId)?.label || ''
        }
        if (values.staffId) {
          newVals.staffName = staffOptions.value.find(item => item.value === values.staffId)?.label || ''
        }
        try {
          await addProject(newVals)
        } finally {
          openModal(false)
          reload()
          createMessage.success('新建项目成功')
        }
      }

      return {
        showModalFn,
        registerTable,
        options,
        handleSearch,
        registerModal,
        registerForm,
        submitModal,
        formElRef,
        hasPermission,
        RoleEnum
      }
    }
  })
</script>
