<script setup lang="ts">
import AForm from '@/components/AForm/index.vue'
import { FormConfigType } from '@/components/AForm/type'
import { ToolbarConfigType } from '@/components/AToolbar/type'
import { ColumnConfigType } from '@/components/ATable/type'
import { StrAnyObj, StrAnyObjArr } from '@/typings'
import { useHandleData } from '@/utils/useHandleData'
import {
  getPageApi,
  getDetailApi,
  addApi,
  editApi,
  deleteApi,
  getStatistics
} from '@/api/business/contract/info'
import Detail from './detail.vue'
import TransactionDetail from './transaction-detail.vue'
import OrderDetail from './order-detail.vue'

const queryRef = ref<InstanceType<typeof AForm>>()
const formRef = ref<InstanceType<typeof AForm>>()

const showQuery = ref<boolean>(true)
const selectKeys = ref<string[]>([])
const pageTotal = ref<number>(0)
const activeName = ref<string>('1')

const queryData = ref<StrAnyObj>({ pageNum: 1, pageSize: 10 })
const tableData = ref<StrAnyObjArr>([])
const statisticsData = ref<StrAnyObjArr>([])
const formData = ref<StrAnyObj>({})

const dialogTitle = ref<string>('')
const dialogVisible = ref<boolean>(false)

const queryConfig: FormConfigType[] = [
  {
    type: 'input',
    prop: 'contractNo',
    label: '合同编号'
  },
  {
    type: 'select',
    prop: 'status',
    label: '合同状态',
    option: [
      {
        key: 10,
        label: '进行中'
      },
      {
        key: 20,
        label: '已完成'
      },
    ]
  },
  {
    type: 'datePicker',
    prop: 'createTime',
    label: '签订日期',
    datePickerType: 'daterange',
    defaultTime: [new Date(0, 0, 0, 0, 0, 0), new Date(0, 0, 0, 23, 59, 59)]
  }
]

const toolbarConfig: ToolbarConfigType[] = [
  {
    common: 'search',
    click() {
      queryData.value.pageNum = 1
      getPage()
    }
  },
  {
    common: 'reset',
    click() {
      queryRef.value?.resetFields()
      getPage()
    }
  }
]

const columnConfig: ColumnConfigType[] = [
  {
    prop: 'contractNo',
    label: '合同编号'
  },
  {
    prop: 'signingDate',
    label: '签订日期',
    formatter: (row) => {
      return row.signingDate.substr(0, 10)
    }
  },
  {
    prop: 'startDate',
    label: '开始日期',
    formatter: (row) => {
      return row.startDate.substr(0, 10)
    }
  },
  {
    prop: 'endDate',
    label: '结束日期',
    formatter: (row) => {
      return row.endDate.substr(0, 10)
    }
  },
  {
    prop: 'sellerCompany',
    label: '归属公司'
  },
  {
    prop: 'customerName',
    label: '客户'
  },
  {
    prop: 'currency',
    label: '币种'
  },
  {
    prop: 'exchangeRate',
    label: '汇率'
  },
  {
    prop: 'costPrice',
    label: '成本价'
  },
  {
    prop: 'freightPrice',
    label: '运费'
  },
  {
    prop: 'insurance',
    label: '保险费'
  },
  {
    slot: 'receivedAmount',
    label: '到账金额'
  },
  {
    prop: 'amount',
    label: '合同金额'
  },
  {
    label: '预期收益',
    formatter: (row) => {
      return Math.round((row.amount - row.costPrice) * 100) / 100
    }
  },
  {
    prop: 'profit',
    label: '实际收益'
  },
  {
    prop: 'status',
    label: '合同状态',
    formatter: (row) => {
      return row.status == 10 ? '进行中' : '已完成'
    }
  },
  {
    width: 120,
    handleConfig: [
      {
        common: 'detail',
        click(row) {
          formData.value = row
          dialogVisible.value = true
          activeName.value = '1'
          dialogTitle.value = '详情'
        }
      }
    ]
  }
]

const formConfig: FormConfigType[] = [
  {
    type: 'input',
    prop: 'contractNo',
    label: '合同编号',
    rule: [{ required: true, message: '合同编号不能为空', trigger: 'blur' }]
  },
  {
    type: 'input',
    prop: 'type',
    label: '合同类型 1-三梵合同，2-佰易来合同',
    rule: [
      { required: true, message: '合同类型 1-三梵合同，2-佰易来合同不能为空', trigger: 'blur' }
    ]
  },
  {
    type: 'input',
    prop: 'contractSubjectId',
    label: '合同主体id',
    rule: [{ required: true, message: '合同主体id不能为空', trigger: 'blur' }]
  },
  {
    type: 'input',
    prop: 'purchaseType',
    label: '采购类型 1-一件商品，2-批单商品',
    rule: [{ required: true, message: '采购类型 1-一件商品，2-批单商品不能为空', trigger: 'blur' }]
  },
  {
    type: 'input',
    prop: 'isTax',
    label: '是否含税（1是 0否）',
    rule: [{ required: true, message: '是否含税（1是 0否）不能为空', trigger: 'blur' }]
  },
  {
    type: 'input',
    prop: 'rankId',
    label: '等级id',
    rule: [{ required: true, message: '等级id不能为空', trigger: 'blur' }]
  },
  {
    type: 'input',
    prop: 'status',
    label: '合同状态 10进行中 20已完成',
    rule: [{ required: true, message: '合同状态 10进行中 20已完成不能为空', trigger: 'blur' }]
  },
  {
    type: 'input',
    prop: 'packingStatus',
    label: '包装状态 0未包装 1已包装',
    rule: [{ required: true, message: '包装状态 0未包装 1已包装不能为空', trigger: 'blur' }]
  },
  {
    type: 'input',
    prop: 'paymentType',
    label: '支付类型 1银行卡支付 2支付宝支付',
    rule: [{ required: true, message: '支付类型 1银行卡支付 2支付宝支付不能为空', trigger: 'blur' }]
  },
  {
    type: 'input',
    prop: 'sellAccountName',
    label: '卖家账户名',
    rule: [{ required: true, message: '卖家账户名不能为空', trigger: 'blur' }]
  },
  {
    type: 'input',
    prop: 'sellBankName',
    label: '卖家开户银行',
    rule: [{ required: true, message: '卖家开户银行不能为空', trigger: 'blur' }]
  },
  {
    type: 'input',
    prop: 'sellBankAccount',
    label: '卖家银行账号',
    rule: [{ required: true, message: '卖家银行账号不能为空', trigger: 'blur' }]
  },
  {
    type: 'input',
    prop: 'sellBankCnapsCode',
    label: '卖家联行号',
    rule: [{ required: true, message: '卖家联行号不能为空', trigger: 'blur' }]
  },
  {
    type: 'input',
    prop: 'sellBeneficiaryName',
    label: '卖家账户名称（外汇信息）',
    rule: [{ required: true, message: '卖家账户名称（外汇信息）不能为空', trigger: 'blur' }]
  },
  {
    type: 'input',
    prop: 'sellBeneficiaryBank',
    label: '卖家开户银行（外汇信息）',
    rule: [{ required: true, message: '卖家开户银行（外汇信息）不能为空', trigger: 'blur' }]
  },
  {
    type: 'input',
    prop: 'sellBeneficiaryBankAccount',
    label: '卖家账号（外汇信息）',
    rule: [{ required: true, message: '卖家账号（外汇信息）不能为空', trigger: 'blur' }]
  },
  {
    type: 'input',
    prop: 'sellBeneficiaryBankAddress',
    label: '卖家开户银行地址（外汇信息）',
    rule: [{ required: true, message: '卖家开户银行地址（外汇信息）不能为空', trigger: 'blur' }]
  },
  {
    type: 'input',
    prop: 'sellSwiftCode',
    label: '卖家银行代码（外汇信息）',
    rule: [{ required: true, message: '卖家银行代码（外汇信息）不能为空', trigger: 'blur' }]
  },
  {
    type: 'input',
    prop: 'sellBeneficiaryAddress',
    label: '卖家收款人地址（外汇信息）',
    rule: [{ required: true, message: '卖家收款人地址（外汇信息）不能为空', trigger: 'blur' }]
  },
  {
    type: 'input',
    prop: 'sellAlipayAccount',
    label: '卖家支付宝账号',
    rule: [{ required: true, message: '卖家支付宝账号不能为空', trigger: 'blur' }]
  },
  {
    type: 'input',
    prop: 'signingDate',
    label: '签订日期',
    rule: [{ required: true, message: '签订日期不能为空', trigger: 'blur' }]
  },
  {
    type: 'input',
    prop: 'startDate',
    label: '开始日期',
    rule: [{ required: true, message: '开始日期不能为空', trigger: 'blur' }]
  },
  {
    type: 'input',
    prop: 'endDate',
    label: '结束日期',
    rule: [{ required: true, message: '结束日期不能为空', trigger: 'blur' }]
  },
  {
    type: 'input',
    prop: 'validityDate',
    label: '报价有效期(天)',
    rule: [{ required: true, message: '报价有效期(天)不能为空', trigger: 'blur' }]
  },
  {
    type: 'input',
    prop: 'customerId',
    label: '客户id',
    rule: [{ required: true, message: '客户id不能为空', trigger: 'blur' }]
  },
  {
    type: 'input',
    prop: 'customerName',
    label: '客户名称',
    rule: [{ required: true, message: '客户名称不能为空', trigger: 'blur' }]
  },
  {
    type: 'input',
    prop: 'customerTelNum',
    label: '客户联系电话',
    rule: [{ required: true, message: '客户联系电话不能为空', trigger: 'blur' }]
  },
  {
    type: 'input',
    prop: 'customerCountry',
    label: '客户国家',
    rule: [{ required: true, message: '客户国家不能为空', trigger: 'blur' }]
  },
  {
    type: 'input',
    prop: 'customerAddress',
    label: '客户地址',
    rule: [{ required: true, message: '客户地址不能为空', trigger: 'blur' }]
  },
  {
    type: 'input',
    prop: 'destination',
    label: '目的地',
    rule: [{ required: true, message: '目的地不能为空', trigger: 'blur' }]
  },
  {
    type: 'input',
    prop: 'shippingMethod',
    label: '货运方式',
    rule: [{ required: true, message: '货运方式不能为空', trigger: 'blur' }]
  },
  {
    type: 'input',
    prop: 'deliveryTerms',
    label: '交货条款',
    rule: [{ required: true, message: '交货条款不能为空', trigger: 'blur' }]
  },
  {
    type: 'input',
    prop: 'deliveryTime',
    label: '交货时间(天)',
    rule: [{ required: true, message: '交货时间(天)不能为空', trigger: 'blur' }]
  },
  {
    type: 'input',
    prop: 'paymentTerms',
    label: '付款条件',
    rule: [{ required: true, message: '付款条件不能为空', trigger: 'blur' }]
  },
  {
    type: 'input',
    prop: 'warrantyPeriod',
    label: '保修时间(天)',
    rule: [{ required: true, message: '保修时间(天)不能为空', trigger: 'blur' }]
  },
  {
    type: 'input',
    prop: 'currency',
    label: '币种',
    rule: [{ required: true, message: '币种不能为空', trigger: 'blur' }]
  },
  {
    type: 'input',
    prop: 'exchangeRate',
    label: '汇率',
    rule: [{ required: true, message: '汇率不能为空', trigger: 'blur' }]
  },
  {
    type: 'input',
    prop: 'freightPrice',
    label: '运费',
    rule: [{ required: true, message: '运费不能为空', trigger: 'blur' }]
  },
  {
    type: 'input',
    prop: 'insurance',
    label: '保险费',
    rule: [{ required: true, message: '保险费不能为空', trigger: 'blur' }]
  },
  {
    type: 'input',
    prop: 'amount',
    label: '金额',
    rule: [{ required: true, message: '金额不能为空', trigger: 'blur' }]
  },
  {
    type: 'input',
    prop: 'remark',
    label: '备注',
    rule: [{ required: true, message: '备注不能为空', trigger: 'blur' }]
  },
  {
    type: 'input',
    prop: 'createBy',
    label: '创建者',
    rule: [{ required: true, message: '创建者不能为空', trigger: 'blur' }]
  },
  {
    type: 'input',
    prop: 'createTime',
    label: '创建时间',
    rule: [{ required: true, message: '创建时间不能为空', trigger: 'blur' }]
  },
  {
    type: 'input',
    prop: 'updateBy',
    label: '更新者',
    rule: [{ required: true, message: '更新者不能为空', trigger: 'blur' }]
  },
  {
    type: 'input',
    prop: 'updateTime',
    label: '最后更新时间',
    rule: [{ required: true, message: '最后更新时间不能为空', trigger: 'blur' }]
  },
  {
    type: 'input',
    prop: 'delFlag',
    label: '删除标志（0代表存在 1代表删除）',
    rule: [{ required: true, message: '删除标志（0代表存在 1代表删除）不能为空', trigger: 'blur' }]
  },
  {
    type: 'input',
    prop: 'tenantId',
    label: '租户id',
    rule: [{ required: true, message: '租户id不能为空', trigger: 'blur' }]
  }
]

onMounted(() => {
  getPage()
})

function getPage() {
  if (queryData.value.createTime && queryData.value.createTime.length > 0) {
    queryData.value.startDate = queryData.value.createTime[0]
    queryData.value.endDate = queryData.value.createTime[1]
  }

  getPageApi(queryData.value).then((resp: StrAnyObjArr) => {
    tableData.value = resp.records
    pageTotal.value = resp.total
  })
  getStatistics(queryData.value).then((res: StrAnyObjArr) => {
    statisticsData.value = res
  })
}

function tableSelectionChange(item: StrAnyObjArr) {
  selectKeys.value = item.map((item) => item.id)
}

function formSubmit() {
  formRef.value?.validate(() => {
    if (formData.value.id) {
      editApi(formData.value).then(() => {
        dialogVisible.value = false
        ElMessage.success('修改成功')
        getPage()
      })
    } else {
      addApi(formData.value).then(() => {
        dialogVisible.value = false
        ElMessage.success('新增成功')
        getPage()
      })
    }
  })
}

function formClosed() {
  formRef.value?.resetFields()
}

function handleRemove(idList: string[]) {
  useHandleData('是否确认删除？', () => {
    deleteApi({ idList }).then(() => {
      ElMessage.success('删除成功')
      getPage()
    })
  })
}
</script>

<template>
  <div>
    <el-card v-if="showQuery">
      <a-form ref="queryRef" v-model="queryData" :config="queryConfig" :span="6"> </a-form>
    </el-card>
    <el-card style="margin-top: 10px">
      <div style="display: flex; flex-wrap: wrap">
        <div
          v-for="(item, index) in statisticsData"
          :key="index"
          style="
            width: calc(25% - 10px);
            padding: 20px;
            background-color: #b0e2ffa8;
            margin-right: 10px;
            border-radius: 10px;
          "
        >
          <div style="font-size: 18px; font-weight: bold; color: black">
            {{ item.sellerCompany }}
          </div>
          <div style="display: flex; color: #ce00ff; font-weight: bold; padding-top: 6px">
            <div style="width: 25%">{{ item.contractQuantity }}</div>
            <div style="width: 25%">{{ item.contractAmount }}</div>
            <div style="width: 25%">{{ item.fundReceivedAmount }}</div>
            <div style="width: 25%">{{ item.profit }}</div>
          </div>
          <div style="display: flex; padding-top: 6px">
            <div style="width: 25%">合同数量</div>
            <div style="width: 25%">合同金额</div>
            <div style="width: 25%">到账金额</div>
            <div style="width: 25%">实际收益</div>
          </div>
        </div>
      </div>
    </el-card>

    <a-table
      :data="tableData"
      :page-total="pageTotal"
      :toolbar-config="toolbarConfig"
      :column-config="columnConfig"
      v-model:showQuery="showQuery"
      v-model:page-num="queryData.pageNum"
      v-model:page-size="queryData.pageSize"
      @page-num-change="getPage"
      @page-size-change="getPage"
      @selection-change="tableSelectionChange"
    >
      <template #receivedAmount="{ row }">
        <div>
          <el-popover placement="bottom" :width="400">
            <template #reference>
              <a style="color: #409eff; cursor: pointer; word-break: break-all">
                {{ row.receivedAmount }}
              </a>
            </template>
            <div v-if="row.capitalTransactionsList && row.capitalTransactionsList.length > 0">
              <el-table :data="row.capitalTransactionsList" :border="false" style="width: 100%">
                <el-table-column label="到账金额" prop="amount" width="100" />
                <el-table-column label="用户" prop="nickname" width="100" />
                <el-table-column label="到账时间" prop="tradingTime" min-width="100" />
              </el-table>
            </div>
          </el-popover>
        </div>
      </template>
    </a-table>

    <a-dialog
      v-if="dialogVisible"
      v-model="dialogVisible"
      :title="dialogTitle"
      @submit="formSubmit"
      @closed="formClosed"
      style="width: 1100px"
      :footer="false"
    >
      <el-tabs v-model="activeName" type="card">
        <el-tab-pane label="合同详情" name="1">
          <Detail :rowData="formData"></Detail>
        </el-tab-pane>
        <el-tab-pane label="交易明细" name="2">
          <TransactionDetail :rowData="formData"></TransactionDetail>
        </el-tab-pane>
        <el-tab-pane label="订单明细" name="3">
          <OrderDetail :rowData="formData"></OrderDetail>
        </el-tab-pane>
      </el-tabs>
    </a-dialog>
  </div>
</template>
