<template>
  <div class="container">
    <a-scrollbar
      :style="{
        height: `calc(${containerHeight} - 150px)`,
        overflow: 'auto',
        background: ' var(--color-bg-2)'
      }"
    >
      <a-card class="general-card">
        <div class="item-container">
          <a-space :size="16" direction="vertical" fill>
            <a-alert :show-icon="false">基本信息</a-alert>
            <a-row
              style="width: 90%; margin: 0 auto; padding: 0px 0px 20px 0px"
              :gutter="[20, 20]"
            >
              <a-col :span="8">
                <div style="" class="editor-descriptions-container">
                  <div style="" class="editor-descriptions-label">
                    合同名称：
                  </div>
                  <div class="editor-descriptions-content" style="">
                    <HoverEditorDetail
                      v-model="modifyParams.data.name"
                      placeholder="项目名称"
                      :not-allow-null="true"
                      :components-type="ComponentsType.STRINGINPUT"
                      @modify="modifyDetail"
                    />
                  </div>
                </div>
              </a-col>
              <a-col :span="8">
                <div style="" class="editor-descriptions-container">
                  <div style="" class="editor-descriptions-label">
                    项目编码：
                  </div>
                  <div class="editor-descriptions-content" style="">
                    {{ detail.contract?.id }}
                  </div>
                </div>
              </a-col>
              <a-col :span="8">
                <div style="" class="editor-descriptions-container">
                  <div style="" class="editor-descriptions-label">签订人：</div>
                  <div class="editor-descriptions-content" style="">
                    <HoverEditorDetail
                      v-model="modifyParams.data.handler_id"
                      placeholder="签订人"
                      :options="accountList"
                      :components-type="ComponentsType.SELECT"
                      @modify="modifyDetail"
                    />
                  </div>
                </div>
              </a-col>
              <a-col :span="8">
                <div style="" class="editor-descriptions-container">
                  <div style="" class="editor-descriptions-label">
                    合同金额：
                  </div>
                  <div class="editor-descriptions-content" style="">
                    <HoverEditorDetail
                      v-model="modifyParams.data.amount"
                      placeholder="合同金额"
                      :not-allow-null="true"
                      :precision="4"
                      :components-type="ComponentsType.NUMBERINPUT"
                      input-suffix="万元"
                      @modify="modifyDetail"
                    />
                  </div>
                </div>
              </a-col>
              <a-col :span="8">
                <div style="" class="editor-descriptions-container">
                  <div style="" class="editor-descriptions-label">
                    客户信息：
                  </div>
                  <div class="editor-descriptions-content" style="">
                    <HoverEditorDetail
                      v-if="isAuthCustomer"
                      v-model="modifyParams.data.customer_id"
                      placeholder="客户信息"
                      :options="customerList"
                      :components-type="ComponentsType.SELECT"
                      @modify="modifyDetail"
                    />
                    <template v-else>
                      {{ detail.contract?.customer_name }}</template
                    >
                  </div>
                </div>
              </a-col>
              <a-col :span="8">
                <div style="" class="editor-descriptions-container">
                  <div style="" class="editor-descriptions-label">
                    客户编号：
                  </div>
                  <div class="editor-descriptions-content" style="">
                    {{ detail.contract?.customer_id }}
                  </div>
                </div>
              </a-col>
              <a-col :span="8">
                <div style="" class="editor-descriptions-container">
                  <div style="" class="editor-descriptions-label">
                    签订日期：
                  </div>
                  <div class="editor-descriptions-content" style="">
                    <HoverEditorDetail
                      v-model="modifyParams.data.signed_at"
                      placeholder="签订日期"
                      :not-allow-null="true"
                      :components-type="ComponentsType.DATEPICKER"
                      @modify="modifyDetail"
                    />
                  </div>
                </div>
              </a-col>
              <a-col :span="8">
                <div style="" class="editor-descriptions-container">
                  <div style="" class="editor-descriptions-label">
                    起始日期：
                  </div>
                  <div class="editor-descriptions-content" style="">
                    <HoverEditorDetail
                      v-model="modifyParams.data.begin_at"
                      placeholder="起始日期"
                      :not-allow-null="true"
                      :components-type="ComponentsType.DATEPICKER"
                      @modify="modifyDetail"
                    />
                  </div>
                </div>
              </a-col>
              <a-col :span="8">
                <div style="" class="editor-descriptions-container">
                  <div style="" class="editor-descriptions-label">
                    终止日期：
                  </div>
                  <div class="editor-descriptions-content" style="">
                    <HoverEditorDetail
                      v-model="modifyParams.data.end_at"
                      placeholder="终止日期"
                      :components-type="ComponentsType.DATEPICKER"
                      @modify="modifyDetail"
                    />
                  </div>
                </div>
              </a-col>
              <a-col :span="8">
                <div style="" class="editor-descriptions-container">
                  <div style="" class="editor-descriptions-label">
                    项目名称：
                  </div>
                  <div class="editor-descriptions-content" style="">
                    {{ detail.contract?.prj_name }}
                  </div>
                </div>
              </a-col>
              <a-col :span="16">
                <div style="" class="editor-descriptions-container">
                  <div style="" class="editor-descriptions-label">
                    项目编码：
                  </div>
                  <div class="editor-descriptions-content" style="">
                    {{ detail.contract?.prj_id }}
                  </div>
                </div>
              </a-col>
              <a-col :span="24">
                <div style="" class="editor-descriptions-container">
                  <div style="" class="editor-descriptions-label">
                    合同摘要：
                  </div>
                  <div class="editor-descriptions-content" style="">
                    <HoverEditorDetail
                      v-model="modifyParams.data.comment"
                      placeholder="合同摘要"
                      :components-type="ComponentsType.TEXTAREA"
                      @modify="modifyDetail"
                    />
                  </div>
                </div>
              </a-col>
            </a-row>
            <a-alert :show-icon="false">收款约定</a-alert>
            <a-form
              ref="contractFormRef"
              :model="modifyParams.data"
              :auto-label-width="true"
              label-align="right"
            >
              <a-table
                class="payment-table"
                :columns="tableColumns"
                :data="modifyParams.data.payments"
                :table-layout-fixed="true"
                :pagination="false"
                row-class="query-row-class"
                :stripe="false"
                :bordered="{
                  cell: true,
                  headerCell: true,
                  wrapper: true
                }"
                :hoverable="false"
              >
                <template #index="{ rowIndex }">
                  {{ rowIndex + 1 }}
                </template>
                <template #condition="{ rowIndex }">
                  <a-form-item
                    v-if="modifyParams.data.payments![rowIndex].isCreated"
                    no-style
                    feedback
                    :field="`payments[${rowIndex}].condition`"
                    :validate-trigger="['change', 'input']"
                    :rules="{
                      required: true
                    }"
                  >
                    <a-input
                      v-model="modifyParams.data.payments![rowIndex].condition"
                      placeholder="收款条件"
                    />
                  </a-form-item>
                  <HoverEditorDetail
                    v-else
                    v-model="modifyParams.data.payments![rowIndex].condition"
                    placeholder="收款条件"
                    :components-type="ComponentsType.STRINGINPUT"
                    @modify="modifyDetail"
                  />
                </template>
                <template #percent="{ rowIndex }">
                  <a-form-item
                    v-if="modifyParams.data.payments![rowIndex].isCreated"
                    no-style
                    feedback
                    :field="`payments[${rowIndex}].percent`"
                    :validate-trigger="['change', 'input']"
                    :rules="{
                      required: true
                    }"
                  >
                    <a-input-number
                      v-model="modifyParams.data.payments![rowIndex].percent"
                      hide-button
                      :precision="2"
                      :max="100"
                      :allow-clear="false"
                      :min="0"
                      placeholder="收款约定"
                    >
                      <template #suffix>%</template>
                    </a-input-number>
                  </a-form-item>
                  <HoverEditorDetail
                    v-else
                    v-model="modifyParams.data.payments![rowIndex].percent"
                    placeholder="收款比例"
                    input-suffix="%"
                    :precision="2"
                    :components-type="ComponentsType.NUMBERINPUT"
                    @modify="modifyDetail"
                  />
                </template>
                <template #amount="{ rowIndex }">
                  {{
                    Math.round(
                      (modifyParams.data.amount || 0) *
                        modifyParams.data.payments![rowIndex].percent *
                        100
                    ) / 10000
                  }}万元
                </template>
                <template #expect_pay_date="{ rowIndex }">
                  <a-form-item
                    v-if="modifyParams.data.payments![rowIndex].isCreated"
                    no-style
                    :field="`payments[${rowIndex}].expect_pay_date`"
                    feedback
                    :validate-trigger="['change', 'input']"
                    :rules="{
                      required: true
                    }"
                  >
                    <a-date-picker
                      v-model="modifyParams.data.payments![rowIndex].expect_pay_date"
                      hide-button
                      placeholder="预计收款日"
                    >
                    </a-date-picker>
                  </a-form-item>
                  <HoverEditorDetail
                    v-else
                    v-model="modifyParams.data.payments![rowIndex].expect_pay_date"
                    placeholder="预计收款日"
                    :components-type="ComponentsType.DATEPICKER"
                    @modify="modifyDetail"
                  />
                </template>
                <template #memo="{ rowIndex }">
                  <a-form-item
                    v-if="modifyParams.data.payments![rowIndex].isCreated"
                    no-style
                    :field="`payments[${rowIndex}].memo`"
                  >
                    <a-input
                      v-model="modifyParams.data.payments![rowIndex].memo"
                      placeholder="备注信息"
                    >
                    </a-input>
                  </a-form-item>
                  <HoverEditorDetail
                    v-else
                    v-model="modifyParams.data.payments![rowIndex].memo"
                    placeholder="备注信息"
                    :components-type="ComponentsType.STRINGINPUT"
                    @modify="modifyDetail"
                  />
                </template>
                <template #operater="{ rowIndex, record }">
                  <a-space>
                    <a-tooltip content="确认添加收款约定">
                      <a-typography-text
                        v-if="modifyParams.data.payments![rowIndex].isCreated"
                        style="cursor: pointer"
                        type="primary"
                        @click="confirmlAddPayment(record)"
                      >
                        <icon-check-circle :size="20" />
                      </a-typography-text>
                    </a-tooltip>
                    <a-tooltip
                      :content="modifyParams.data.payments![rowIndex].isCreated ? '取消添加收款约定' : '删除收款约定'"
                    >
                      <a-typography-text
                        style="cursor: pointer"
                        type="danger"
                        @click="removePayment(rowIndex, record)"
                      >
                        <icon-stop
                          v-if="modifyParams.data.payments![rowIndex].isCreated"
                          :size="20"
                        />
                        <icon-minus-circle v-else :size="20" />
                      </a-typography-text>
                    </a-tooltip>
                  </a-space>
                </template>
                <template #footer>
                  <a-button type="dashed" long @click="addPayment()"
                    ><template #icon><icon-plus /></template>收款约定</a-button
                  >
                </template>
              </a-table>
            </a-form>
            <a-descriptions
              size="large"
              :label-style="{
                textAlign: 'right',
                width: '100px',
                fontWeight: 'bold',
                paddingRight: '10px',
                paddingBottom: '20px',
                color: 'rgb(var(--gray-8))'
              }"
              :value-style="{ width: '300px', paddingBottom: '20px' }"
            >
              <template #title>
                <a-alert :show-icon="false">合同文档</a-alert>
              </template>
              <a-descriptions-item label="打印件：" :span="3">
                <div
                  v-if="detail.contract?.doc_uploaded"
                  class="upload-container"
                >
                  <div class="file-container">
                    <div class="filename">
                      <icon-font class="list-icon" type="my-doc" :size="20" />
                      &nbsp; {{ detail.contract?.doc_name }}
                    </div>
                  </div>

                  <a-space class="file-extra" style="margin-left: 10px">
                    <a-tooltip content="下载文件">
                      <a-typography-text
                        style="cursor: pointer"
                        type="primary"
                        @click="
                          downloadContractFile(
                            ContractTypeItem.DOC,
                            detail.contract?.id,
                            detail.contract?.doc_name
                          )
                        "
                      >
                        <icon-download :size="19" />
                      </a-typography-text>
                    </a-tooltip>
                    <a-tooltip content="删除文件">
                      <a-typography-text
                        style="cursor: pointer"
                        type="danger"
                        @click="
                          removeFile(ContractTypeItem.DOC, detail.contract?.id)
                        "
                      >
                        <icon-delete :size="18" />
                      </a-typography-text>
                    </a-tooltip>
                  </a-space>
                </div>
                <a-upload
                  v-else
                  draggable
                  accept=".doc,.docx"
                  :auto-upload="false"
                  :limit="1"
                  :show-file-list="false"
                  :on-before-upload="(file: File) => uploadConractFileHandler(file, ContractTypeItem.DOC)
                    "
                >
                  <template #upload-button>
                    <div
                      class="arco-upload-drag"
                      style="
                        border: 1px dashed var(--color-fill-4);
                        height: 80px;
                        border-radius: 2;
                        font-size: 14px;
                        line-height: 80px;
                        text-align: center;
                      "
                    >
                      <div>
                        <span>
                          <IconUpload />
                          将打印件拖入或点击上传附件
                        </span>
                      </div>
                    </div>
                  </template>
                </a-upload>
              </a-descriptions-item>
              <a-descriptions-item label="盖章扫描件：" :span="3">
                <div
                  v-if="detail.contract?.pdf_uploaded"
                  class="upload-container"
                >
                  <div class="file-container">
                    <div class="filename">
                      <icon-font class="list-icon" type="my-pdf" :size="20" />
                      &nbsp; {{ detail.contract?.pdf_name }}
                    </div>
                  </div>

                  <a-space class="file-extra" style="margin-left: 10px">
                    <a-tooltip content="下载文件">
                      <a-typography-text
                        style="cursor: pointer"
                        type="primary"
                        @click="
                          downloadContractFile(
                            ContractTypeItem.PDF,
                            detail.contract?.id,
                            detail.contract?.pdf_name
                          )
                        "
                      >
                        <icon-download :size="19" />
                      </a-typography-text>
                    </a-tooltip>
                    <a-tooltip content="删除文件">
                      <a-typography-text
                        style="cursor: pointer"
                        type="danger"
                        @click="
                          removeFile(ContractTypeItem.PDF, detail.contract?.id)
                        "
                      >
                        <icon-delete :size="18" />
                      </a-typography-text>
                    </a-tooltip>
                  </a-space>
                </div>
                <a-upload
                  v-else
                  draggable
                  accept=".pdf"
                  :auto-upload="false"
                  :limit="1"
                  :show-file-list="false"
                  :on-before-upload="(file: File) => uploadConractFileHandler(file, ContractTypeItem.PDF)
                    "
                >
                  <template #upload-button>
                    <div
                      class="arco-upload-drag"
                      style="
                        border: 1px dashed var(--color-fill-4);
                        height: 80px;
                        border-radius: 2;
                        font-size: 14px;
                        line-height: 80px;
                        text-align: center;
                      "
                    >
                      <div>
                        <span>
                          <IconUpload />
                          将盖章扫描件拖入或点击上传附件
                        </span>
                      </div>
                    </div>
                  </template>
                </a-upload>
              </a-descriptions-item>
            </a-descriptions>
          </a-space>
        </div>
      </a-card>
    </a-scrollbar>
  </div>
</template>

<script lang="ts" setup>
import { reactive, onMounted, nextTick, PropType, ref, watch } from 'vue'
import { ComponentsType, ContractTypeItem, IconFontUrl } from '@/enums/api'
import { TableColumnData } from '@arco-design/web-vue/es/table/interface'
import HoverEditorDetail from '@/components/hover-editor-detail/index.vue'
import {
  getDownloadContractFileUrl,
  removeContractFile,
  getContractDetail,
  modifyContract,
  getUploadContractFileUrl
} from '@/api/project/contract'

import {
  Payment,
  ContractDetailResParams,
  ModifyContractReqParams
} from '@/types/contract'
import Message from '@arco-design/web-vue/es/message'
import { useEmitt } from '@/logics/mitt/useEmitt'
import { FormInstance } from '@arco-design/web-vue/es/form'
import IconDelete from '@arco-design/web-vue/es/icon/icon-delete'
import IconDownload from '@arco-design/web-vue/es/icon/icon-download'
import { uploadFile } from '@/api/client'
import { Icon } from '@arco-design/web-vue'
import { downloadFile } from '@/utils/download'

const IconFont = Icon.addFromIconFontCn({
  src: IconFontUrl.URL
})
const detail = reactive<{ contract?: ContractDetailResParams }>({
  contract: undefined
}) // 合同详情
const contractFormRef = ref<FormInstance>()
const { emitter } = useEmitt()
const props = defineProps({
  contractId: {
    type: String,
    required: false
  },
  containerHeight: {
    type: String,
    default: () => {
      return '100vh'
    }
  },
  accountList: {
    type: Array as PropType<{ id: string; name: string }[]>
  },
  isAuthCustomer: {
    type: Boolean
  },
  customerList: {
    type: Array as PropType<{ id: string; name: string }[]>,
    default: () => {
      return []
    }
  }
})

const modifyParams = reactive<{ data: Omit<ModifyContractReqParams, 'id'> }>({
  data: {}
})

const tableColumns: TableColumnData[] = [
  {
    title: '序号',
    dataIndex: 'index',
    slotName: 'index',
    width: 100
  },
  {
    title: '收款条件',
    dataIndex: 'condition',
    bodyCellClass: 'miniCellPadding',
    slotName: 'condition'
  },
  {
    title: '收款比例',
    dataIndex: 'percent',
    slotName: 'percent',
    width: 150
  },
  {
    title: '收款金额（万元）',
    dataIndex: 'amount',
    bodyCellClass: 'miniCellPadding',
    slotName: 'amount',
    align: 'center',
    width: 200
  },
  {
    title: '预计收款日',
    dataIndex: 'expect_pay_date',
    bodyCellClass: 'miniCellPadding',
    slotName: 'expect_pay_date',
    width: 200
  },
  {
    title: '备注',
    dataIndex: 'memo',
    bodyCellClass: 'miniCellPadding',
    slotName: 'memo'
  },
  {
    title: '',
    slotName: 'operater',
    bodyCellClass: 'operater',
    align: 'center',
    width: 80
  }
]

/**
 * 获取客户详情
 * @param customerId
 */
const getDetail = async (contractId: string) => {
  const contractDetail = await getContractDetail(contractId)
  nextTick(() => {
    detail.contract = contractDetail
    modifyParams.data.name = contractDetail.name
    modifyParams.data.amount = contractDetail.amount
    modifyParams.data.customer_id = contractDetail.customer_id
    modifyParams.data.handler_id = contractDetail.handler_id
    modifyParams.data.signed_at = contractDetail.signed_at
    modifyParams.data.begin_at = contractDetail.begin_at
    modifyParams.data.end_at = contractDetail.end_at
    modifyParams.data.comment = contractDetail.comment
    modifyParams.data.payments = contractDetail.payments || []
  })
}

// 添加未确认付款约定，
const addPayment = () => {
  modifyParams.data.payments?.push({
    isCreated: true,
    condition: '',
    percent: 0, // 收款比例
    expect_pay_date: '',
    memo: undefined
  })
}

// 删除付款约定
const removePayment = async (index: number, record: Payment) => {
  modifyParams.data.payments?.splice(index, 1)
  if (record.isCreated) {
    return
  }
  await modifyDetail()
}

// 添加后，确认完成添加付款约定
const confirmlAddPayment = async (record: Payment) => {
  const isValid = await contractFormRef.value?.validate()
  if (isValid) {
    return
  }
  delete record.isCreated
  await modifyDetail()
}

// 修改信息
const modifyDetail = async () => {
  const { payments, ...elseObj } = modifyParams.data
  const params: ModifyContractReqParams = {
    id: props.contractId!,
    ...elseObj,
    payments: payments?.filter(item => !item.isCreated)
  }
  await modifyContract(params)
  Message.success('修改成功')
  emitter.emit('get_customer_list')
}

// 上传合同打印件
const uploadConractFileHandler = async (file: File, type: ContractTypeItem) => {
  const { url, form_data: data } = await getUploadContractFileUrl({
    id: props.contractId!,
    type_id: type,
    filename: file.name
  })
  await uploadFile(url, {
    data,
    file
  })
  if (type === ContractTypeItem.DOC) {
    detail.contract!.doc_uploaded = true
    detail.contract!.doc_name = file.name
  } else {
    detail.contract!.pdf_uploaded = true
    detail.contract!.pdf_name = file.name
  }
  Message.success('上传成功')
  return true
}

// 下载合同文件
const downloadContractFile = async (
  type: ContractTypeItem,
  contractId?: string,
  filename?: string
) => {
  const { url } = await getDownloadContractFileUrl({
    id: contractId!,
    type_id: type
  })
  downloadFile(url, filename!)
  return true
}

/**
 * 删除合同文件
 * @param contractId
 * @param type
 */
const removeFile = async (type: ContractTypeItem, contractId?: string) => {
  await removeContractFile({
    id: contractId!,
    type_id: type
  })
  if (type === ContractTypeItem.DOC) {
    detail.contract!.doc_uploaded = false
  } else {
    detail.contract!.pdf_uploaded = false
  }
  Message.success('删除成功，可重新上传')
}

watch(
  () => props.contractId,
  () => {
    getDetail(props.contractId!)
  }
)

onMounted(() => {
  if (props.contractId) {
    getDetail(props.contractId)
  }
})
</script>

<style lang="less" scoped>
.container {
  padding: 20px 20px 20px 20px;

  .general-card {
    :deep(.arco-card-header) {
      padding: 20px 20px 0 20px;
    }

    .item-container {
      padding-top: 20px;

      :deep(.arco-descriptions-item-label) {
        font-weight: normal;
      }
    }
  }
}

:deep(.arco-alert) {
  text-align: center;
  font-size: 16px;
}

:deep(.arco-table-th) {
  background: none;
}

// :deep(.arco-descriptions-row):nth-child(3),
// :deep(.arco-descriptions-row):nth-child(4),

.payment-table {
  :deep(.query-row-class) {
    .operater {
      .arco-table-cell {
        padding: 0px;
      }
    }
  }

  :deep(.arco-table-footer) {
    padding: 3px;
  }
}

:deep(.arco-upload-drag) {
  padding: 0;
}

.upload-container {
  position: relative;
  display: flex;
  align-items: center;
  box-sizing: border-box;

  .file-container {
    display: flex;
    // flex: 1;
    flex-wrap: nowrap;
    align-items: center;
    box-sizing: border-box;
    background-color: var(--color-fill-1);
    padding: 8px 150px 8px 12px;
    overflow: hidden;
    font-size: 14px;
    border-radius: var(--border-radius-small);
    transition: background-color 0.1s cubic-bezier(0, 0, 1, 1);

    .filename {
      display: flex;
      flex: 1;
      align-items: center;
      margin-right: 10px;
      overflow: hidden;
      color: var(--color-text-1);
      font-size: 14px;
      line-height: 1.4286;
      white-space: nowrap;
      text-overflow: ellipsis;
    }

    .file-extra {
      margin-left: 20px;
      color: var(--color-text-2);
    }
  }
}
</style>
