<template>
  <div class="w-50vw">
    <basic-form @register="register" @submit="handleSubmit" />
  </div>
</template>
<script lang="ts">
  import { defineComponent, computed, unref, PropType } from 'vue'
  import { BasicForm, FormSchema, useForm } from '/@/components/Form/index'
  import { ProjectStatusEnum } from '/@/enums/statusEnum'
  import { useOfficeStore } from '/@/store/modules/office'
  import { ProjectListItem, ProjectUpdateOrCreateParams } from '/@/api/sys/model/projectModel'
  import { onMountedOrActivated } from '/@/hooks/core/onMountedOrActivated'
  import { updateProject } from '/@/api/sys/project'
  import { useMessage } from '/@/hooks/web/useMessage'
  import { propTypes } from '/@/utils/propTypes'

  export default defineComponent({
    components: {
      BasicForm
    },
    props: {
      info: {
        type: Object as PropType<ProjectListItem>,
        required: true
      },
      hasPermission: propTypes.bool
    },
    emits: ['updateInfo:info'],
    setup(props, { emit }) {
      const info = computed({
        get: () => props.info,
        set: value => emit('updateInfo:info', value)
      })

      const { createMessage } = useMessage()
      const officeStore = useOfficeStore()
      const options = computed(() =>
        officeStore.getCategoryOptions.map(item => ({ label: item.label, value: item.label }))
      )
      const staffOptions = computed(() => officeStore.getCategoriedStaff)

      const schemas = computed<FormSchema[]>(() => [
        {
          field: 'status',
          component: 'RadioGroup',
          label: '状态',
          componentProps: {
            options: [
              {
                label: '正常',
                value: ProjectStatusEnum.NORMAL
              },
              {
                label: '停用',
                value: ProjectStatusEnum.STOP
              }
            ],
            disabled: !props.hasPermission
          }
        },
        {
          field: 'createName',
          component: 'Input',
          label: '创建者',
          componentProps: {
            disabled: true
          }
        },
        {
          field: 'code',
          component: 'Input',
          label: '项目编号',
          componentProps: {
            disabled: true
          }
        },
        {
          field: 'name',
          component: 'Input',
          label: '项目名称',
          disabled: !props.hasPermission,
          required: true
        },
        {
          field: 'insideCategory',
          component: 'Select',
          componentProps: {
            options,
            showArrow: true,
            disabled: !props.hasPermission
          },
          label: '所在办事处',
          required: true
        },
        {
          field: 'category',
          component: 'Select',
          label: '销售负责人',
          componentProps: {
            options,
            showArrow: true,
            disabled: !props.hasPermission
          },
          colProps: {
            span: 14
          },
          required: true
        },
        {
          field: 'staffName',
          component: 'Select',
          disabledLabelWidth: true,
          componentProps: {
            options: staffOptions,
            showArrow: true,
            disabled: !props.hasPermission
          },
          label: '',
          colProps: {
            span: 8,
            offset: 2
          },
          required: true
        },
        {
          field: 'staffPhone',
          component: 'Input',
          label: '负责人电话'
        },
        {
          field: 'staffQq',
          component: 'Input',
          label: '负责人QQ'
        },
        {
          field: 'staffTelephone',
          component: 'Input',
          label: '负责人座机'
        },
        {
          field: 'remark',
          component: 'InputTextArea',
          componentProps: {
            disabled: !props.hasPermission
          },
          label: '备注'
        }
      ])
      const [register, { updateSchema, setFieldsValue }] = useForm({
        labelWidth: 120,
        schemas,
        showActionButtonGroup: props.hasPermission,
        actionColOptions: {
          flex: '280px',
          span: 14
        },
        submitButtonOptions: {
          text: '确认修改'
        }
      })
      async function checkOffice() {
        officeStore.checkStaffList()
        if (props.info.category) {
          await officeStore.getStaffWithCategoryIdAction({ category: props.info.category })
        }
      }
      checkOffice()
      onMountedOrActivated(async () => {
        await updateSchema([
          {
            field: 'insideCategory',
            component: 'Select',
            label: '所在办事处',
            componentProps: { options, showArrow: true },
            required: true
          },
          {
            field: 'category',
            component: 'Select',
            label: '销售负责人',
            componentProps: {
              options,
              showArrow: true,
              onChange: (value: string) => {
                officeStore.getStaffWithCategoryIdAction({ category: value })
              }
            },
            colProps: {
              span: 14
            },
            required: true
          }
        ])
        await setFieldsValue({ ...unref(info) })
      })

      const handleOnSave = async (values: {
        name: string
        insideCategory: string
        category: string
        staffName: string
        remark: string
        status: string
      }) => {
        const newVal: ProjectUpdateOrCreateParams = {
          ...values,
          id: props.info.id,
          insideCategory: '',
          category: ''
        }
        if (values.insideCategory) {
          newVal.insideCategory = options.value.find(item => item.value === values.insideCategory)?.label || ''
        }
        if (values.category) {
          newVal.category = options.value.find(item => item.value === values.category)?.label || ''
        }
        // if (values.staffName) {
        //   newVal.staffName = staffOptions.value.find(item => item.value === values.staffId)?.label || ''
        // }
        try {
          await updateProject(newVal)
        } catch (error) {
          return false
        }
        info.value = { ...info.value, ...newVal }
        return true
      }
      async function handleSubmit(values) {
        const result = await handleOnSave(values)
        result && createMessage.success('更新成功')
      }
      return { register, schemas, handleSubmit }
    }
  })
</script>
