<template>
  <div class="">
    <vModal
      v-model:visible="visibleDeviceModal"
      :title="modalTitle"
      :width="800"
      @modal-handle-ok="modelHandleOk"
      @modal-handle-cancel="modelHandleCancel"
    >
      <div style="padding: 5px 15px">
        <a-form
          ref="customerFormRef"
          :model="customerForm"
          :auto-label-width="true"
          label-align="right"
          :rules="customerFormRules"
        >
          <a-form-item label="客户名称" field="name">
            <a-input v-model="customerForm.name" placeholder="请输入客户名称" />
          </a-form-item>
          <a-form-item label="客户行业" field="industryId">
            <a-select
              v-model="customerForm.industryId"
              placeholder="请选择行业类型"
            >
              <a-option
                v-for="{ id, name } in industryList"
                :key="id"
                :value="id"
                :label="`${name}`"
              ></a-option>
            </a-select>
          </a-form-item>
          <a-form-item label="客户级别" field="levelId">
            <a-select
              v-model="customerForm.levelId"
              placeholder="请选择客户级别"
            >
              <a-option
                v-for="{ id, name } in levelList"
                :key="id"
                :value="id"
                :label="`${name}`"
              ></a-option>
            </a-select>
          </a-form-item>
          <a-form-item label="所在地区" field="regionId">
            <a-cascader
              v-model="customerForm.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="客户联系"
            :content-flex="false"
            :merge-props="false"
          >
            <a-row :gutter="6">
              <a-col :span="12">
                <a-form-item field="linkMan" no-style>
                  <a-input
                    v-model="customerForm.linkMan"
                    placeholder="客户联系人"
                  />
                </a-form-item>
              </a-col>
              <a-col :span="12">
                <a-form-item field="linkPhone" no-style>
                  <a-input
                    v-model="customerForm.linkPhone"
                    placeholder="联系人电话"
                  />
                </a-form-item>
              </a-col>
            </a-row>
          </a-form-item>
          <a-form-item label="客户地址" field="address">
            <a-input
              v-model="customerForm.address"
              placeholder="请输入客户实际经营地址"
            />
          </a-form-item>
          <a-form-item label="市场负责人" field="bizmanId">
            <a-select
              v-model="customerForm.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="intro">
            <a-textarea
              v-model="customerForm.memo"
              placeholder="请输入客户备注信息"
              :show-word-limit="true"
              :max-length="256"
              :auto-size="{
                minRows: 3
              }"
            >
            </a-textarea>
          </a-form-item>
          <a-form-item>
            <a-typography-text
              type="primary"
              style="cursor: pointer; margin-left: auto; font-size: 16px"
              @click="toggle()"
            >
              <icon-double-right
                :style="{
                  transform: !showMore ? 'rotate(90deg)' : 'rotate(0deg)'
                }"
              />开票资料
            </a-typography-text>
          </a-form-item>
          <a-form-item
            v-if="!showMore"
            :content-flex="false"
            :merge-props="false"
            no-style
          >
            <a-row :gutter="20">
              <a-col :span="12">
                <a-form-item field="invoiceTitle" label="发票抬头">
                  <a-input
                    v-model="customerForm.invoiceTitle"
                    placeholder="输入客户发票抬头"
                  />
                </a-form-item>
              </a-col>
              <a-col :span="12">
                <a-form-item field="taxNo" label="客户税号">
                  <a-input
                    v-model="customerForm.taxNo"
                    placeholder="输入客户税号"
                  />
                </a-form-item>
              </a-col>
            </a-row>
          </a-form-item>
          <a-form-item
            v-if="!showMore"
            :content-flex="false"
            :merge-props="false"
            no-style
          >
            <a-row :gutter="20">
              <a-col :span="12">
                <a-form-item field="bankName" label="客户开户行">
                  <a-input
                    v-model="customerForm.bankName"
                    placeholder="输入客户开户行"
                  />
                </a-form-item>
              </a-col>
              <a-col :span="12">
                <a-form-item field="bankAccount" label="开户行账号">
                  <a-input
                    v-model="customerForm.bankAccount"
                    placeholder="输入客户开户行账号"
                  />
                </a-form-item>
              </a-col>
            </a-row>
          </a-form-item>
          <a-form-item
            v-if="!showMore"
            :content-flex="false"
            :merge-props="false"
            no-style
          >
            <a-row :gutter="20">
              <a-col :span="12">
                <a-form-item field="invoiceAddr" label="开户行地址">
                  <a-input
                    v-model="customerForm.invoiceAddr"
                    placeholder="输入客户开户行地址"
                  />
                </a-form-item>
              </a-col>
              <a-col :span="12">
                <a-form-item field="invoicePhone" label="开户行电话">
                  <a-input
                    v-model="customerForm.invoicePhone"
                    placeholder="输入客户开户行电话"
                  />
                </a-form-item>
              </a-col>
            </a-row>
          </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 { addCustomer, removeCustomer } from '@/api/biz/customer'
import { DomainTree } from '@/types/domain'
import { AddCustomerReqParams } from '@/types/customer'
import { useToggle } from '@vueuse/core'

const [showMore, toggle] = useToggle()
const customerFormRef = ref<FormInstance>()
const visibleDeviceModal = ref(false) // 是否显示对话框
const modalType = ref(0) // 对话框类型，0：添加，1：修改
const modalTitle = ref('') // 对话框标题
defineProps({
  regionTreeData: {
    type: Array as PropType<DomainTree[]>
  },
  industryList: {
    type: Array as PropType<{ id: string; name: string }[]>
  },
  levelList: {
    type: Array as PropType<{ id: string; name: string }[]>
  },
  accountList: {
    type: Array as PropType<{ id: string; name: string }[]>
  }
})

const customerForm = reactive<{
  name?: string
  industryId?: string
  regionId?: number
  levelId?: string
  linkMan?: string
  linkPhone?: string
  address?: string
  invoiceTitle?: string
  taxNo?: string
  bankName?: string
  bankAccount?: string
  invoiceAddr?: string
  invoicePhone?: string
  bizmanId?: string
  memo?: string
}>({})

const customerFormRules = {
  name: [{ required: true, message: '客户名称不能为空', trigger: 'blur' }],
  industryId: [
    { required: true, message: '行业类型不能为空', trigger: 'blur' }
  ],
  regionId: [{ required: true, message: '所在区域不能为空', trigger: 'blur' }],

  levelId: [{ required: true, message: '客户级别不能为空', trigger: 'blur' }]
}

const { emitter } = useEmitt()

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

/**
 * 显示级别modal
 * @param type modal 类型
 * @param item
 */
const showCustomerModal = async () => {
  modalTitle.value = `新建客户`
  visibleDeviceModal.value = true
}

/**
 * 点击确认按钮时，cb(false)时不会继续后续操作
 * @param cb 回调函数，
 */
const modelHandleOk = async (cb: (closed: boolean) => void) => {
  const isValid = await customerFormRef.value?.validate()
  if (isValid) {
    return cb(false)
  }
  const {
    name,
    industryId,
    regionId,
    levelId,
    linkMan,
    linkPhone,
    address,
    invoiceTitle,
    taxNo,
    bankName,
    bankAccount,
    invoiceAddr,
    invoicePhone,
    memo,
    bizmanId
  } = customerForm
  const isAdd = modalType.value === 0
  if (isAdd) {
    const params: AddCustomerReqParams = {
      name: name!,
      industry_id: industryId!,
      region_id: regionId!,
      level_id: levelId!,
      link_man: linkMan,
      link_phone: linkPhone,
      address,
      invoice_title: invoiceTitle,
      tax_no: taxNo,
      bank_name: bankName,
      bank_account: bankAccount,
      invoice_addr: invoiceAddr,
      invoice_phone: invoicePhone,
      bizman_id: bizmanId,
      memo
    }
    await addCustomer(params)
    emitter.emit('get_customer_list')
    Message.success('添加成功')
  }
  return cb(true)
}

/**
 * 删除客户信息
 * @param m
 */
const handleRemoveCustomer = 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 removeCustomer(id)
      emitter.emit('get_customer_list')
      Message.success('删除成功')
    }
  })
}

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

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