<template>
  <PageWrapper>
    <BasicTable @register="registerTable">
      <template #toolbar>
        <div class="w-2/5 flex">
          <Search @search="value => handleSearch('search', value)" placeholder="项目名称/项目编号" />
          <a-button @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 { 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'

  export default defineComponent({
    name: 'Workbench',
    components: {
      PageWrapper,
      BasicTable,
      Search: Input.Search,
      ASelect: Select,
      BasicModal,
      BasicForm,
      PlusOutlined
    },
    setup() {
      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: '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: '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.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
      }
    }
  })
</script>
