<template>
  <div class="">
    <vModal
      v-model:visible="visibleDeviceModal"
      :title="modalTitle"
      :ok-loading="loading"
      :width="800"
      @modal-handle-ok="modelHandleOk"
      @modal-handle-cancel="modelHandleCancel"
    >
      <div style="padding: 5px 15px">
        <a-form
          ref="contractFormRef"
          :model="contractForm"
          :auto-label-width="true"
          label-align="right"
          :rules="contractFormRules"
        >
          <a-form-item label="合同名称" field="name">
            <a-input v-model="contractForm.name" placeholder="请输入合同名称" />
          </a-form-item>
          <a-form-item label="合同客户" field="customerId">
            <a-select
              v-model="contractForm.customerId"
              placeholder="请选择合同客户"
            >
              <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="prjId">
            <a-select
              v-model="contractForm.prjId"
              placeholder="请选择合同项目"
              :allow-clear="true"
              @popup-visible-change="visibleProjectList"
            >
              <a-option
                v-for="{ id, name } in projectList"
                :key="id"
                :value="id"
                :label="`${name}`"
              ></a-option>
            </a-select>
          </a-form-item>
          <a-form-item label="合同金额" field="amount">
            <a-input-number
              v-model="contractForm.amount"
              hide-button
              :precision="4"
              placeholder="请输入合同金额"
            >
              <template #suffix> 万元 </template>
            </a-input-number>
          </a-form-item>
          <a-form-item label="合同签订" field="handlerId">
            <a-select
              v-model="contractForm.handlerId"
              placeholder="请选择合同签订人"
            >
              <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="signedAt">
            <a-date-picker
              v-model="contractForm.signedAt"
              style="width: 100%"
              placeholder="请选择合同签订日期"
            ></a-date-picker>
          </a-form-item>
          <a-form-item label="合同起始" field="beginAt">
            <a-date-picker
              v-model="contractForm.beginAt"
              style="width: 100%"
              placeholder="请选择合同起始日期"
            ></a-date-picker>
          </a-form-item>
          <a-form-item label="合同结束" field="endAt">
            <a-date-picker
              v-model="contractForm.endAt"
              style="width: 100%"
              placeholder="请选择合同结束日期"
            ></a-date-picker>
          </a-form-item>
          <a-form-item label="合同摘要" field="comment">
            <a-textarea
              v-model="contractForm.comment"
              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 no-style>
            <a-table
              v-if="!showMore"
              class="payment-table"
              :columns="tableColumns"
              :data="contractForm.payments"
              :table-layout-fixed="true"
              row-class="query-row-class"
              :pagination="false"
              :bordered="{
                cell: true,
                headerCell: true,
                wrapper: true
              }"
              :hoverable="false"
            >
              <template #condition="{ rowIndex }">
                <a-form-item
                  no-style
                  :field="`payments[${rowIndex}].condition`"
                  feedback
                  :validate-trigger="['change', 'input']"
                  :rules="{
                    required: true
                  }"
                >
                  <a-input
                    v-model="contractForm.payments![rowIndex].condition"
                    placeholder="收款条件"
                  />
                </a-form-item>
              </template>
              <template #percent="{ rowIndex }">
                <a-form-item
                  no-style
                  :field="`payments[${rowIndex}].percent`"
                  feedback
                  :validate-trigger="['change', 'input']"
                  :rules="{
                    required: true
                  }"
                >
                  <a-input-number
                    v-model="contractForm.payments![rowIndex].percent"
                    hide-button
                    :max="100"
                    :precision="2"
                    :allow-clear="false"
                    :min="0"
                    placeholder="收款比例"
                  >
                    <template #suffix>%</template>
                  </a-input-number>
                </a-form-item>
              </template>
              <template #expect_pay_date="{ rowIndex }">
                <a-form-item
                  no-style
                  :field="`payments[${rowIndex}].expect_pay_date`"
                  feedback
                  :validate-trigger="['change', 'input']"
                  :rules="{
                    required: true
                  }"
                >
                  <a-date-picker
                    v-model="contractForm.payments![rowIndex].expect_pay_date"
                    hide-button
                    placeholder="预计收款日"
                  >
                    <template #suffix-icon>{{}}</template>
                  </a-date-picker>
                </a-form-item>
              </template>
              <template #amount="{ rowIndex }">
                {{
                  Math.round(
                    (contractForm.amount || 0) *
                      contractForm.payments![rowIndex].percent *
                      100
                  ) / 10000
                }}万元
              </template>
              <template #footer>
                <a-button type="dashed" long @click="addPayment()"
                  ><template #icon><icon-plus /></template>收款约定</a-button
                >
              </template>
              <template #operater="{ rowIndex }">
                <div class="operate-text-button">
                  <a-button
                    type="text"
                    status="danger"
                    @click="removePayment(rowIndex)"
                    ><template #icon> <icon-minus-circle :size="20" /></template
                  ></a-button>
                </div>
              </template>
            </a-table>
          </a-form-item>
          <!-- <a-form-item>
            <a-button type="outline" long
              ><template #icon><icon-plus /></template>添加收款约定</a-button
            >
          </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 { useToggle } from '@vueuse/core'
import { AddContractReqParams, Payment } from '@/types/contract'
import { TableColumnData } from '@arco-design/web-vue/es/table/interface'
import { addContract, removeContract } from '@/api/project/contract'
import { getProjectList } from '@/api/project/info'

const [showMore, toggle] = useToggle()
const contractFormRef = ref<FormInstance>()
const visibleDeviceModal = ref(false) // 是否显示对话框
const modalType = ref(0) // 对话框类型，0：添加，1：修改
const modalTitle = ref('') // 对话框标题

defineProps({
  // projectList: {
  //   type: Array as PropType<{ id: string; name: string }[]>
  // },
  customerList: {
    type: Array as PropType<{ id: string; name: string }[]>
  },
  accountList: {
    type: Array as PropType<{ id: string; name: string }[]>
  }
})

const projectList = ref<{ id: string; name: string }[]>([]) // 分组树

const contractForm = reactive<{
  name?: string
  prjId?: string
  handlerId?: string
  signedAt?: string
  amount?: number
  customerId?: string
  beginAt?: string
  endAt?: string
  comment?: string
  payments?: Payment[]
}>({
  payments: []
})

// const getpaymentsAmount = (percent: number) => {
//   if(contractForm.amount)
// }

const contractFormRules = {
  name: [{ required: true, message: '合同名称不能为空', trigger: 'blur' }],
  handlerId: [
    { required: true, message: '合同签订人不能为空', trigger: 'blur' }
  ],
  signedAt: [
    { required: true, message: '合同签订日期不能为空', trigger: 'blur' }
  ],

  amount: [{ required: true, message: '合同金额不能为空', trigger: 'blur' }],
  customerId: [
    { required: true, message: '客户信息不能为空', trigger: 'blur' }
  ],
  beginAt: [{ required: true, message: '合同起始日不能为空', trigger: 'blur' }]
  // condition: [{ required: true, message: '收款条件不能为空', trigger: 'blur' }],
  // percent: [{ required: true, message: '收款比例不能为空', trigger: 'blur' }],
  // expect_pay_date: [
  //   { required: true, message: '预计收款日不能为空', trigger: 'blur' }
  // ]
}

const { emitter } = useEmitt()
const loading = ref<boolean>(false)
const tableColumns: TableColumnData[] = [
  {
    title: '收款条件',
    dataIndex: 'condition',
    bodyCellClass: 'miniCellPadding',
    slotName: 'condition'
  },
  {
    title: '收款比例',
    dataIndex: 'percent',
    bodyCellClass: 'miniCellPadding',
    slotName: 'percent',
    width: 100
  },
  {
    title: '收款金额',
    slotName: 'amount',
    align: 'center',
    width: 130
  },
  {
    title: '预计收款日',
    dataIndex: 'expect_pay_date',
    bodyCellClass: 'miniCellPadding',
    slotName: 'expect_pay_date',
    width: 180
  },
  {
    title: '',
    slotName: 'operater',
    bodyCellClass: 'miniCellPadding',
    width: 50
  }
]

const addPayment = () => {
  contractForm.payments?.push({
    condition: '',
    percent: 0, // 收款比例
    expect_pay_date: '',
    memo: undefined
  })
}

const removePayment = (index: number) => {
  contractForm.payments?.splice(index, 1)
}

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

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

/**
 * 点击确认按钮时，cb(false)时不会继续后续操作
 * @param cb 回调函数，
 */
const modelHandleOk = async (cb: (closed: boolean) => void) => {
  const isValid = await contractFormRef.value?.validate()
  if (isValid) {
    return cb(false)
  }
  const {
    name,
    prjId,
    handlerId,
    signedAt,
    amount,
    customerId,
    beginAt,
    endAt,
    comment,
    payments
  } = contractForm
  const isAdd = modalType.value === 0
  if (isAdd) {
    try {
      const params: AddContractReqParams = {
        name: name!,
        prj_id: prjId,
        handler_id: handlerId!,
        signed_at: signedAt!,
        amount: amount!,
        customer_id: customerId!,
        begin_at: beginAt!,
        end_at: endAt,
        comment,
        payments
      }
      await addContract(params)
      emitter.emit('get_contract_list')
      Message.success('添加成功')
      return cb(true)
    } catch (e) {
      loading.value = false
      return cb(false)
    }
  }
  return cb(false)
}

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

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

/**
 * 获取项目列表
 */
const getProjects = async () => {
  try {
    const { list } = await getProjectList({ page_no: 1, page_size: 9999 })
    projectList.value = list
  } catch (e) {
    console.error(e)
  }
}

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

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

<style lang="less" scoped>
.payment-table {
  :deep(.query-row-class) {
    .miniCellPadding {
      .arco-table-cell {
        padding: 6px;
      }
    }
  }
  :deep(.arco-table-footer) {
    padding: 3px;
  }
}
</style>
