<template>
  <div class="">
    <vModal
      v-model:visible="visibleDeviceModal"
      :title="modalTitle"
      :ok-loading="loading"
      :mask-closable="false"
      @modal-handle-ok="modelHandleOk"
      @modal-handle-cancel="modelHandleCancel"
    >
      <div style="padding: 5px 15px">
        <a-form
          ref="prjFormRef"
          :model="prjForm"
          :auto-label-width="true"
          label-align="right"
          :rules="prjFormRules"
        >
          <a-form-item label="项目名称" field="name">
            <a-input v-model="prjForm.name" placeholder="请输入项目名称" />
          </a-form-item>
          <a-form-item label="所在地区" field="regionId">
            <a-cascader
              v-model="prjForm.regionId"
              :options="regionTreeData"
              :field-names="{
                value: 'id',
                label: 'name'
              }"
              :allow-search="false"
              :allow-clear="true"
              placeholder="全部"
              :max-tag-count="1"
              check-strictly
            />
          </a-form-item>
          <a-form-item label="项目类型" field="typeId">
            <a-cascader
              v-model="prjForm.typeId"
              :options="prjTypeTreeData"
              :field-names="{
                value: 'id',
                label: 'name'
              }"
              :allow-search="false"
              :allow-clear="true"
              placeholder="全部"
              :max-tag-count="1"
            />
          </a-form-item>
          <a-form-item label="客户信息" field="customerId">
            <a-select
              v-model="prjForm.customerId"
              placeholder="请选择客户信息"
              allow-clear
              allow-search
              @popup-visible-change="visibleCustomer"
            >
              <a-option
                v-for="{ id, name } in customerList"
                :key="id"
                :value="id"
                :label="name"
              ></a-option>
            </a-select>
          </a-form-item>
          <a-form-item label="合同信息" field="contractId">
            <a-select
              v-model="prjForm.contractId"
              placeholder="请选择合同信息"
              @popup-visible-change="visibleContract"
            >
              <a-option
                v-for="{ id, name } in contractList"
                :key="id"
                :value="id"
                :label="`${name}`"
              ></a-option>
            </a-select>
          </a-form-item>
          <a-form-item label="预计交付" field="deliverAt">
            <a-date-picker v-model="prjForm.deliverAt" style="width: 100%" />
          </a-form-item>
          <!-- <a-form-item label="项目负责人" field="leaderId">
            <a-select
              v-model="prjForm.leaderId"
              placeholder="请选择项目负责人"
              allow-search
              allow-clear
            >
              <a-option
                v-for="{ id, name } in accountList"
                :key="id"
                :value="id"
                :label="name"
              >
              </a-option>
            </a-select>
          </a-form-item> -->
          <!-- <a-form-item label="商务负责人" field="bizmanId">
            <a-select
              v-model="prjForm.bizmanId"
              placeholder="请选择商务负责人"
              allow-search
              allow-clear
            >
              <a-option
                v-for="{ id, name } in accountList"
                :key="id"
                :value="id"
                :label="name"
              >
              </a-option>
            </a-select>
          </a-form-item> -->
          <a-form-item label="审核组成员" field="checkerids">
            <a-select
              v-model="prjForm.checkerids"
              placeholder="请选择项审核组成员"
              allow-search
              multiple
              allow-clear
            >
              <a-option
                v-for="{ id, name } in accountList"
                :key="id"
                :value="id"
                :label="name"
              >
              </a-option>
            </a-select>
          </a-form-item>
          <a-form-item label="项目简介" field="intro">
            <a-textarea
              v-model="prjForm.intro"
              placeholder="请输入项目简介信息"
              :show-word-limit="true"
              :max-length="256"
              :auto-size="{
                minRows: 3
              }"
            >
            </a-textarea>
          </a-form-item>
        </a-form>
      </div>
    </vModal>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, h, PropType } from 'vue'
import { FormInstance } from '@arco-design/web-vue/es/form'
import { Modal, Message } from '@arco-design/web-vue'
import vModal from '@/components/modal/index.vue'
import { useEmitt } from '@/logics/mitt/useEmitt'

import { addProject, removeProject } from '@/api/project/info'
import { DomainTree } from '@/types/domain'
import { AddProjectReqParams } from '@/types/project'
import { Customer, CustomerListReqParams } from '@/types/customer'
import { getCustomerList } from '@/api/biz/customer'
import { getContractList } from '@/api/project/contract'

const loading = ref<boolean>(false)
const prjFormRef = ref<FormInstance>()
const visibleDeviceModal = ref(false) // 是否显示对话框
const modalType = ref(0) // 对话框类型，0：添加，1：修改
const modalTitle = ref('') // 对话框标题

defineProps({
  regionTreeData: {
    type: Array as PropType<DomainTree[]>
  },
  accountList: {
    type: Array as PropType<{ id: string; name: string }[]>
  },
  prjTypeTreeData: {
    type: Array as PropType<DomainTree[]>
  }
})

const prjForm = reactive<{
  customerId?: string
  name?: string
  regionId?: number
  typeId?: number
  templateId?: string
  contractId?: string
  deliverAt?: string
  // leaderId?: string
  // bizmanId?: string
  intro?: string
  checkerids?: string[]
}>({})

const prjFormRules = {
  typeId: [{ required: true, message: '项目类型不能为空', trigger: 'blur' }],
  regionId: [{ required: true, message: '所在区域不能为空', trigger: 'blur' }],
  name: [{ required: true, message: '项目名称不能为空', trigger: 'blur' }],
  // bizmanId: [
  //   { required: true, message: '商务负责人不能为空', trigger: 'blur' }
  // ],
  deliverAt: [
    { required: true, message: '预计交付时间不能为空', trigger: 'blur' }
  ],
  // leaderId: [
  //   { required: true, message: '项目负责人不能为空', trigger: 'blur' }
  // ],
  checkerids: [
    { required: true, message: '审核组成员不能为空', trigger: 'blur' }
  ]
}

const { emitter } = useEmitt()
const customerList = ref<Customer[]>([])
const contractList = ref<{ id: string; name: string }[]>([])

// 显示客户可选列表
const visibleCustomer = (visible: boolean) => {
  if (visible) {
    getCustomers()
  }
}

// 显示合同可选列表
const visibleContract = (visible: boolean) => {
  if (visible) {
    getContracts()
  }
}

/**
 * 隐藏model 对话框，重置表单
 */
const modelHandleCancel = () => {
  return prjFormRef.value!.resetFields() // 初始化表单值
}

/**
 * 显示级别modal
 * @param type modal 类型
 * @param item
 */
const showProjectModal = async () => {
  try {
    modalTitle.value = `创建项目`
    visibleDeviceModal.value = true
  } catch (e) {
    console.log(e)
  }
}

/**
 * 点击确认按钮时，cb(false)时不会继续后续操作
 * @param cb 回调函数，
 */
const modelHandleOk = async (cb: (closed: boolean) => void) => {
  const isValid = await prjFormRef.value?.validate()
  if (isValid) {
    return cb(false)
  }
  try {
    const {
      customerId,
      name,
      regionId,
      typeId,
      templateId,
      contractId,
      deliverAt,
      // leaderId,
      // bizmanId,
      intro,
      checkerids
    } = prjForm
    const isAdd = modalType.value === 0
    if (isAdd) {
      const params: AddProjectReqParams = {
        customer_id: customerId === '' ? undefined : customerId,
        name: name!,
        region_id: regionId!,
        type_id: typeId!,
        template_id: templateId,
        contract_id: contractId === '' ? undefined : contractId,
        deliver_at: deliverAt!,
        // leader_id: leaderId!,
        // bizman_id: bizmanId!,
        intro,
        checker_ids: checkerids!
      }
      await addProject(params)
      emitter.emit('get_project_list')
      Message.success('添加成功')
    }
    return cb(true)
  } catch (e) {
    loading.value = false
    return cb(false)
  }
}

/**
 * 删除项目信息
 * @param m
 */
const handleRemoveProject = async (id: string, name: string) => {
  const title = {
    setup() {
      return () => h('strong', '警告')
    }
  }
  const ModalContent = {
    setup() {
      return () =>
        h('span', { style: 'margin-left: 10px;' }, [
          h('span', `确认删除 `),
          h('strong', `${name}`),
          h('span', ` 吗？`)
        ])
    }
  }
  Modal.warning({
    title: () => h(title),
    content: () => h(ModalContent),
    alignCenter: true,
    titleAlign: 'start',
    draggable: true,
    escToClose: true,
    width: 300,
    simple: true,
    hideCancel: false,
    onOk: async () => {
      await removeProject(id)
      emitter.emit('get_project_list')
      Message.success('删除成功')
    }
  })
}

// 获取客户列表
const getCustomers = async (name?: string) => {
  try {
    const params: CustomerListReqParams = {
      page_no: 1,
      page_size: 9999,
      name
    }
    const { list } = await getCustomerList(params)
    customerList.value = list
  } catch (e) {
    console.error(e)
  }
}

const getContracts = async (name?: string) => {
  try {
    const { list } = await getContractList({
      page_no: 1,
      page_size: 9999,
      binded: false
    })
    contractList.value = list
  } catch (e) {
    console.error(e)
  }
}

defineExpose({ showProjectModal, handleRemoveProject }) // 暴露子组件的方法或者数据
</script>

<script lang="ts">
export default {
  name: 'ProjectCURD'
}
</script>
