<template>
  <div>
    <el-form :model="searchForm" label-width="0" inline>
      <el-form-item>
        <el-input v-model="searchForm.signId" placeholder="成交单号" clearable />
      </el-form-item>
      <el-form-item>
        <el-input v-model="searchForm.name" placeholder="线索名称" clearable />
      </el-form-item>
      <el-form-item>
        <el-select v-model="searchForm.state" placeholder="审核状态" clearable style="width: 120px">
          <el-option label="待审核" :value="1" />
          <el-option label="已撤销" :value="2" />
          <el-option label="已通过" :value="3" />
          <el-option label="已驳回" :value="4" />
        </el-select>
      </el-form-item>
      <el-form-item v-if="appStore.getAppInfo?.instanceType == 1">
        <el-select
          v-model="searchForm.receiver"
          placeholder="接待人"
          clearable
          filterable
          style="width: 120px"
        >
          <el-option
            v-for="item in allUserOptions"
            :key="item.id"
            :label="item.nickname"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item v-else-if="appStore.getAppInfo?.instanceType == 2">
        <el-select
          v-model="searchForm.convertPeople"
          placeholder="转化人"
          clearable
          filterable
          style="width: 120px"
        >
          <el-option
            v-for="item in allUserOptions"
            :key="item.id"
            :label="item.nickname"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-select
          v-model="searchForm.signUser"
          placeholder="登记人"
          clearable
          filterable
          style="width: 120px"
        >
          <el-option
            v-for="item in userOptions"
            :key="item.id"
            :label="item.nickname"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-date-picker
          v-model="searchForm.dealDate"
          type="daterange"
          format="YYYY-MM-DD"
          value-format="YYYY-MM-DD"
          range-separator="-"
          start-placeholder="成交日期"
          end-placeholder="成交日期"
          style="width: 240px"
        />
      </el-form-item>
      <el-form-item>
        <el-select
          v-model="searchForm.applyUser"
          placeholder="申请人"
          clearable
          filterable
          style="width: 120px"
        >
          <el-option
            v-for="item in userOptions"
            :key="item.id"
            :label="item.nickname"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-date-picker
          v-model="searchForm.applyTime"
          type="daterange"
          format="YYYY-MM-DD"
          value-format="YYYY-MM-DD"
          range-separator="-"
          start-placeholder="申请日期"
          end-placeholder="申请日期"
          style="width: 240px"
        />
      </el-form-item>
      <el-form-item>
        <el-date-picker
          v-model="searchForm.checkTime"
          type="daterange"
          format="YYYY-MM-DD"
          value-format="YYYY-MM-DD"
          range-separator="-"
          start-placeholder="审核日期"
          end-placeholder="审核日期"
          style="width: 240px"
        />
      </el-form-item>
      <el-form-item>
        <el-button @click="handleSearch" v-hasPermi="['clue:order:return-search']">查询</el-button>
        <el-button @click="handleReset" v-hasPermi="['clue:order:return-reset']">重置</el-button>
        <el-button @click="batchAudit" v-hasPermi="['clue:order:return-batch-audit']">
          批量审核
        </el-button>
      </el-form-item>
    </el-form>

    <el-table
      v-loading="loading"
      :data="tableList"
      border
      show-summary
      :summary-method="getSummaries"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="60" :selectable="(row) => row.state == 1" />
      <el-table-column prop="signId" label="成交单号" min-width="180px" />
      <el-table-column prop="name" label="线索名称" width="150px" />
      <el-table-column prop="phone" label="联系方式" width="120px" />companyProfit
      <el-table-column prop="money" label="回款金额" min-width="120px">
        <template #default="{ row }">
          <el-input-number
            v-if="row.edit"
            v-model="row.money"
            size="small"
            :min="0"
            :controls="false"
            style="width: 100%"
          />
          <div v-else>{{ row.money }}</div>
        </template>
      </el-table-column>
      <el-table-column
        v-if="appStore.getAppInfo?.instanceType == 1"
        prop="companyProfit"
        label="公司利润"
        min-width="120px"
      >
        <template #default="{ row }">
          <el-input-number
            v-if="row.edit"
            v-model="row.companyProfit"
            size="small"
            :min="0"
            :controls="false"
            style="width: 100%"
          />
          <div v-else>{{ row.companyProfit }}</div>
        </template>
      </el-table-column>
      <el-table-column
        v-if="appStore.getAppInfo?.instanceType == 1"
        prop="personProfit"
        label="员工利润"
        min-width="120px"
      >
        <template #default="{ row }">
          <el-input-number
            v-if="row.edit"
            v-model="row.personProfit"
            size="small"
            :min="0"
            :controls="false"
            style="width: 100%"
          />
          <div v-else>{{ row.personProfit }}</div>
        </template>
      </el-table-column>
      <el-table-column prop="signPrice" label="成交价" min-width="90" />
      <el-table-column prop="isPayoff" label="是否结清" min-width="90">
        <template #default="{ row }">
          <el-select v-if="row.edit" size="small" v-model="row.isPayoffValue">
            <el-option label="结清" :value="true" />
            <el-option label="未结清" :value="false" />
          </el-select>
          <div v-else>{{ row.isPayoff }}</div>
        </template>
      </el-table-column>
      <el-table-column
        v-if="appStore.getAppInfo?.instanceType == 1"
        prop="receiverName"
        label="接待人"
        min-width="90"
      />
      <el-table-column
        v-else-if="appStore.getAppInfo?.instanceType == 2"
        prop="convertPeopleName"
        label="转化人"
        min-width="90"
      />
      <el-table-column prop="signUserName" label="登记人" min-width="90" />
      <el-table-column
        prop="dealDate"
        label="成交日期"
        min-width="120px"
        :formatter="dateFormatter"
      />
      <el-table-column prop="applyUserName" label="申请人" min-width="90" />
      <el-table-column
        prop="applyTime"
        label="申请时间"
        min-width="120px"
        :formatter="dateFormatter"
      />
      <el-table-column prop="checkUser" label="审核人" min-width="90" />
      <el-table-column
        prop="checkTime"
        label="审核时间"
        min-width="120px"
        :formatter="dateFormatter"
      />
      <el-table-column prop="stateName" label="审核状态" fixed="right" min-width="90" />
      <el-table-column label="操作" width="220px" fixed="right">
        <template #default="{ row }">
          <el-button
            type="primary"
            style="padding: 0"
            text
            v-hasPermi="['clue:order:return-detail']"
            @click="handleDetail(row)"
          >
            详情
          </el-button>
          <el-button
            type="primary"
            style="padding: 0"
            text
            v-if="row.state == 1 && currentUserId == row.applyUser"
            v-hasPermi="['clue:order:return']"
            @click="handleCancel(row.id)"
          >
            撤销
          </el-button>
          <el-button
            type="primary"
            style="padding: 0"
            text
            v-if="row.state == 1"
            v-hasPermi="['clue:order:update-return-money']"
            @click="handleUpdate(row)"
          >
            <span>{{ row.edit ? '保存' : '修改金额' }}</span>
          </el-button>
          <el-button
            type="primary"
            style="padding: 0"
            text
            v-if="row.state == 1"
            v-hasPermi="['clue:order:return-audit']"
            @click="handleAudit(row)"
          >
            审核
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <Pagination
      v-model:limit="searchForm.pageSize"
      v-model:page="searchForm.pageNo"
      :total="total"
      @pagination="getList"
    />

    <DialogFeebackAudit ref="feebackDialog" @success="getList" />
    <DialogFeebackDetail ref="feebackDetailDialog" />
    <DialogBatchAudit ref="batchAuditDialog" @success="getList" />
  </div>
</template>

<script setup name="Reback">
import * as FeebackApi from '@/api/clue/payment'
import { getSimpleUserList as getUserOption, getAllUserList } from '@/api/system/user'
import { useUserStore } from '@/store/modules/user'

import DialogFeebackAudit from './DialogFeebackAudit.vue'
import DialogFeebackDetail from './DialogFeebackDetail.vue'
import DialogBatchAudit from './DialogBatchAudit.vue'

import { removeNullField } from '@/utils'
import { useAppStore } from '@/store/modules/app'
import { dateFormatter } from '@/utils/formatTime'

const userStore = useUserStore()
const message = useMessage() // 消息弹窗
const appStore = useAppStore()

const feebackDialog = ref()

const currentUserId = userStore.getUser.id

const searchForm = ref({
  signId: undefined,
  name: undefined,
  state: undefined,
  dealDate: [],
  signUser: undefined,
  applyTime: [],
  applyUser: undefined,
  checkTime: [],
  pageNo: 1,
  pageSize: 20
})

const userOptions = ref([])
const allUserOptions = ref([])

const tableList = ref([])
const total = ref(0)

function handleSearch() {
  searchForm.value.pageNo = 1
  getList()
}

function handleReset() {
  searchForm.value = {
    signId: undefined,
    receiver: undefined,
    convertPeople: undefined,
    name: undefined,
    dealDate: [],
    state: undefined,
    signUser: undefined,
    applyTime: [],
    applyUser: undefined,
    checkTime: [],
    pageNo: 1,
    pageSize: 20
  }
}

const totalInfo = ref({})
const loading = ref(false)
async function getList() {
  loading.value = true
  try {
    const data = await FeebackApi.getPaymentPage(removeNullField(searchForm.value))
    tableList.value = data.list
    total.value = data.total
    totalInfo.value = data.totalData
  } finally {
    loading.value = false
  }
}

const batchIds = ref([])
function handleSelectionChange(val) {
  batchIds.value = val.map((it) => it.id)
}

const batchAuditDialog = ref()
function batchAudit() {
  if (batchIds.value.length) {
    batchAuditDialog.value.open('aftersale', batchIds.value)
  } else {
    message.info('请选择表格中需要审核的数据')
  }
}

const feebackDetailDialog = ref()
function handleDetail(row) {
  feebackDetailDialog.value.open(row)
}
async function handleCancel(id) {
  try {
    // 删除的二次确认
    await message.confirm('是否确认撤销申请？')
    // 发起删除
    await FeebackApi.cancelApplyPayment({ id })
    message.success('撤销成功！')
    // 刷新列表
    await getList()
  } catch (err) {
    console.log(err)
  }
}
function handleAudit(row) {
  feebackDialog.value.open(row)
}

function getOptions() {
  getUserOption().then((data) => {
    userOptions.value = data
  })
  getAllUserList().then((data) => {
    allUserOptions.value = data
  })
}

function getSummaries(param) {
  const { columns } = param
  const sums = []
  columns.forEach((column, index) => {
    if (index === 0) {
      sums[index] = '合计'
    } else if (column.property == 'money') {
      sums[index] = totalInfo.value.totalMoney
    } else if (column.property == 'personProfit') {
      sums[index] = totalInfo.value.totalPersonProfit
    } else if (column.property == 'companyProfit') {
      sums[index] = totalInfo.value.totalCompanyProfit
    } else if (column.property == 'signPrice') {
      sums[index] = totalInfo.value.totalSignPrice
    } else {
      sums[index] = ''
    }
  })

  return sums
}

async function handleUpdate(row) {
  if (row.edit) {
    // 删除的二次确认
    await message.confirm('是否确认修改回款金额？')
    // 保存
    FeebackApi.updateApplyPayment({
      id: row.id,
      money: row.money,
      companyProfit: row.companyProfit,
      personProfit: row.personProfit,
      isPayoff: row.isPayoffValue
    })
      .then(() => {
        message.success('修改成功')
        getList()
      })
      .finally(() => {
        row.edit = false
      })
  } else {
    row.edit = true
    row.isPayoffValue = row.isPayoff == '结清'
  }
}

onMounted(() => {
  getOptions()
  handleSearch()
})
</script>

<style lang="scss" scoped></style>
