<template>
  <div class="app-container">
    <el-form v-model="pagerDto" inline>
      <el-form-item label="创建人">
        <el-select
          v-model="pagerDto._Eq_CreateUserName"
          placeholder="创建人"
          clearable
          filterable
        >
          <el-option
            v-for="item in users"
            :key="item.Id"
            :label="item.Name"
            :value="item.Name"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="客户">
        <el-select
          v-model="pagerDto._Eq_CustomerCode"
          placeholder="客户"
          clearable
          filterable
        >
          <el-option
            v-for="item in customers"
            :key="item.Id"
            :label="`${item.CompanyName}(${item.CustomerNumber})`"
            :value="item.CustomerNumber"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="单号类型">
        <el-select
          v-model="pagerDto._Eq_CodeType"
          placeholder="单号类型"
          clearable
        >
          <el-option
            v-for="(item, index) in CodeTypes"
            :key="index"
            :value="item.Id"
            :label="item.Name"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="单号">
        <el-tooltip v-model="openNumbersInput" effect="light" :manual="true">
          <div slot="content">
            <el-input
              v-model="inputMultiCodes"
              type="textarea"
              rows="7"
              placeholder="请输入单号，每行一个"
            />
            <div style="text-align: right; padding: 5px">
              <el-button
                size="mini"
                @click="openNumbersInput = false"
              >关闭</el-button>
              <el-button
                size="mini"
                type="danger"
                @click="inputMultiCodes = ''"
              >清除</el-button>
              <el-button
                size="mini"
                type="success"
                @click="confirmMultiCodes"
              >确定</el-button>
            </div>
          </div>
          <el-input
            v-model="pagerDto._In_Codes"
            clearable
            @focus="openNumbersInputPannel"
          />
        </el-tooltip>
      </el-form-item>

      <el-form-item label="派送渠道">
        <el-select
          v-model="pagerDto._Eq_ChannelId"
          placeholder="派送渠道"
          clearable
          filterable
        >
          <el-option
            v-for="item in channels"
            :key="item.Id"
            :label="item.Name"
            :value="item.Id"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="索赔时间">
        <div class="block">
          <el-date-picker
            v-model="claimTime"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            value-format="yyyy-MM-dd"
            end-placeholder="结束日期"
            @change="ClaimTimeSeleted"
          />
        </div>
      </el-form-item>

      <el-form-item label="索赔状态">
        <el-select
          v-model="pagerDto._Eq_ClaimStatus"
          placeholder="索赔状态"
          clearable
          filterable
        >
          <el-option
            v-for="item in claimStatus"
            :key="item.Id"
            :label="item.Name"
            :value="item.Id"
          />
        </el-select>
      <el-form-item label="欠费拦截状态">
        <el-select
          v-model="pagerDto._Eq_IsInterceptCustomers"
          placeholder="欠费拦截状态"
          clearable
          filterable
        >
          <el-option
            label="拦截"
            :value="true"
          />
          <el-option
            label="不拦截"
            :value="false"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="创建时间">
        <div class="block">
          <el-date-picker
            v-model="pagerDto._Range_CreateTime"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            value-format="yyyy-MM-dd"
            end-placeholder="结束日期"
          />
        </div>
      </el-form-item>


        <el-button
          icon="el-icon-search"
          type="primary"
          @click="searchData"
        >搜索</el-button>
      </el-form-item>
      <div style="margin-bottom: 10px">
        <el-button type="info" @click="changeDepartment">变更责任部门</el-button>
        <el-button type="danger" @click="batchDelete">批量删除</el-button>
        <el-button
          type="success"
          icon="el-icon-upload"
          @click="openUploadClaim"
        >导入索赔记录</el-button>

        <el-button
          :loading="downloading"
          type="primary"
          icon="el-icon-download"
          @click="downClaimRecords"
        >导出记录</el-button>
        <el-button
          :loading="downloading"
          type="success"
          icon="el-icon-s-check"
          plain
          @click="handleCheckDialog('batch')"
        >批量审核</el-button>
      </div>
    </el-form>
    <div class="table-warp">
      <el-table
        v-loading="loading"
        height="660px"
        :data="sourceData"
        border
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" />
        <el-table-column prop="TransferNumber" label="中转单号" width="200" />
        <el-table-column prop="TrackingNumber" label="跟踪号" width="240" />
        <el-table-column prop="CustomerName" label="客户" />
      <el-table-column label="拦截欠费" prop="IsInterceptCustomers">
        <template slot-scope="r">
          <el-tag v-if="r.row.IsInterceptCustomers">是</el-tag>
          <el-tag v-if="!r.row.IsInterceptCustomers" type="info">否</el-tag>
        </template>
        </el-table-column>
        <el-table-column prop="ClaimStatusName" label="索赔状态" width="78" />
        <el-table-column prop="CreateUserName" label="创建人" width="70" />
        <el-table-column prop="CreateTime" label="创建时间" width="90" :formatter="colFormatDate" />
        <el-table-column prop="FinanceConfirmTime" label="索赔时间" width="90" :formatter="colFormatDate" />
        <el-table-column prop="Cost" label="成本">
          <template slot-scope="scope">
            {{ scope.row.Cost }}/{{ scope.row.Cost }}
          </template>
        </el-table-column>
        <el-table-column prop="Freight" label="运费">
          <template slot-scope="scope">
            {{ scope.row.Freight }}/{{ scope.row.Freight }}
          </template>
        </el-table-column>
        <el-table-column prop="TotalValue" label="总价值">
          <template slot-scope="scope">
            {{ scope.row.TotalValue }}/{{ scope.row.TotalValue }}
          </template>
        </el-table-column>
        <el-table-column prop="SolutionName" label="索赔方案" />
        <el-table-column prop="Department" label="责任部门" />
        <el-table-column prop="AuditSolution" label="确认索赔方案" width="110" />
        <el-table-column prop="AuditTotalAmount" label="确认索赔金额" width="110" />
        <el-table-column label="操作" width="90" fixed="right">
          <template slot-scope="scope">
            <div v-show="scope.row.ClaimStatus === 0">
              <el-button
                type="danger"
                size="mini"
                plain
                class="define-button"
                @click="remove(scope.row)"
              >移除</el-button>
              <el-button
                type="primary"
                size="mini"
                plain
                class="define-button"
                @click="handleCheckDialog('single',scope.row)"
              >审核</el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div>
      <el-pagination
        :page-sizes="[100, 200, 300, 400]"
        :current-page="pagerDto.PageIndex"
        :page-size="pagerDto.PageSize"
        background
        layout="prev, pager, next ,total ,jumper,sizes,slot "
        :total="pagerDto.total"
        @current-change="pagerSerach"
      />
    </div>

    <el-dialog
      :visible.sync="openUploadPannel"
      :title="uploadTitle"
      @closed="uploadClosed"
    >
      <div v-loading="uploading" style="text-align: center">
        <el-upload
          ref="upload"
          accept=".xlsx"
          :action="uploadUrl"
          :file-list="fileList"
          :auto-upload="false"
          :headers="headers"
          :on-success="uploadSuccess"
          :on-error="uploadError"
        >
          <el-button
            slot="trigger"
            size="small"
            type="primary"
          >选择文件</el-button>
          <el-button
            style="margin-left: 10px"
            size="small"
            type="success"
            :loading="uploading"
            @click="submitUpload"
          >上传到服务器</el-button>

          <el-link
            type="primary"
            :href="templateUrl"
            style="margin-left: 20px"
          >下载模板</el-link>
          <div slot="tip" class="el-upload__tip"><el-checkbox v-model="IsCheckRepet" :disabled="uploading" @change="IsCheckRepetChange">校验重复</el-checkbox></div>
          <div slot="tip" class="el-upload__tip">只能上传.xlsx文件</div>
        </el-upload>
      </div>
    </el-dialog>
    <el-dialog
      :visible.sync="showUploadError"
      title="导入错误"
      @closed="errorDialogClosed"
    >
      <div>
        <div v-for="(msg, idx) in errorMsgs" :key="idx">{{ msg }}</div>
      </div>
    </el-dialog>
    <!-- 审核弹窗 -->
    <el-dialog
      title="审核"
      :visible.sync="checkVisible"
      width="92%"
      top="3vh"
      custom-class="check-visible"
      :before-close="handleCheckClose"
    >
      <vxe-table
        ref="checkRef"
        class="check-table"
        border
        :data="editCheckData"
        show-footer
        show-overflow
        show-header-overflow
        height="760px"
        :edit-rules="validRules"
        :cell-style="{ height: '38px', padding: 0 }"
        :column-config="{ resizable: true }"
        :edit-config="{trigger: 'click', mode: 'cell'}"
        :merge-cells="getMergeCells"
        :row-class-name="rowClassName"
      >
        <vxe-column field="TotalAmount" title="汇总" width="0">
          <template #default="{ row }">
            <div v-if="row.TotalAmount" class="total-amount-warp">
              <div>汇总</div>
              <div style="width: 90px;">{{ row | getTotalAmount(editCheckData) }}</div>
            </div>
          </template>
        </vxe-column>
        <vxe-column field="CustomerName" title="客户" :min-width="120" />
        <vxe-column field="TransferNumber" title="中转单号" :min-width="170" />
        <vxe-column field="TrackingNumber" title="跟踪号" :min-width="200" />
        <vxe-column field="Department" title="责任部门" :min-width="120" />
        <vxe-colgroup title="成本" align="center">
          <vxe-column field="Cost" title="提交成本" :min-width="100" />
          <vxe-column field="AuditCost" title="确认成本" :min-width="100" class-name="define-cell-bg" :edit-render="{ autofocus: '.cost .el-input__inner' }">
            <template #edit="scope">
              <el-input v-model="scope.row.AuditCost" v-decimal-input type="text" class="cost" placeholder="确认成本" @blur="changeAuditTotalAmount(scope)" />
            </template>
          </vxe-column>
        </vxe-colgroup>
        <vxe-colgroup title="运费" align="center">
          <vxe-column field="Freight" title="提交运费" :min-width="100" />
          <vxe-column field="AuditFreight" title="确认运费" :min-width="100" class-name="define-cell-bg" :edit-render="{ autofocus: '.freight .el-input__inner' }">
            <template #edit="scope">
              <el-input v-model="scope.row.AuditFreight" v-decimal-input type="text" class="freight" placeholder="确认运费" @blur="changeAuditTotalAmount(scope)" />
            </template>
          </vxe-column>
        </vxe-colgroup>
        <vxe-colgroup title="总价值" align="center">
          <vxe-column field="TotalValue" title="提交总价值" :min-width="110" />
          <vxe-column field="AuditTotalValue" title="确认总价值" :min-width="110" class-name="define-cell-bg" :edit-render="{ autofocus: '.total .el-input__inner' }">
            <template #edit="{ row }">
              <el-input v-model="row.AuditTotalValue" v-decimal-input type="text" class="total" placeholder="确认总价值" />
            </template>
          </vxe-column>
        </vxe-colgroup>
        <vxe-colgroup title="索赔方案" align="center">
          <vxe-column field="SolutionName" title="提交索赔方案" :min-width="110" />
          <vxe-column field="AuditSolution" title="确认索赔方案" :min-width="120" class-name="define-cell-bg" :edit-render="{ autofocus: '.audit-textarea .el-textarea__inner' }">
            <template #edit="{ row }">
              <el-input v-model="row.AuditSolution" type="textarea" class="audit-textarea" placeholder="确认索赔方案" />
            </template>
          </vxe-column>
        </vxe-colgroup>
        <vxe-column field="AuditTotalAmount" title="确认赔付金额" :min-width="130" class-name="amount-cell-bg" :edit-render="{ autofocus: '.money .el-input__inner' }">
          <template #edit="scope">
            <el-input v-model="scope.row.AuditTotalAmount" v-decimal-input type="text" class="money" placeholder="确认赔付金额" @input="updateTableStatus(scope)" />
          </template>
        </vxe-column>
      </vxe-table>
      <span slot="footer" class="dialog-footer">
        <el-button @click="handleCheckClose">取 消</el-button>
        <el-button type="primary" :loading="auditCheck" @click="hanleAudit">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import request from '@/utils/request'
import { _getDeliverChannel, _getAllUsers, _getCustomers } from '@/api/baseInfo'
import { getToken } from '@/utils/auth'
import { format } from '@/utils/multiInput'
import colFormatDate from '@/utils/columnFormat'
import { VXETable } from 'vxe-table'
import { floorToDecimals } from '@/utils'
export default {
  name: 'ClaimRecord',
  directives: {
    decimalInput: {
      bind: function(el, binding, vnode) {
        el.handleInput = function handleInput(event) {
          const input = event.target
          const value = input.value
          // 移除非数字字符和超过两位小数的部分
          const newValue = value.replace(/[^0-9.]/g, '').replace(/^\D*(\d*(?:\.\d{0,3})?).*$/g, '$1')
          input.value = newValue
          // 更新双向绑定
          vnode.componentInstance.$emit('input', newValue)
        }
        el.addEventListener('input', el.handleInput)
      },
      unbind(el) {
        el.removeEventListener('input', el.handleInput)
      }
    }
  },
  data() {
    return {
      downloading: false,
      inputMultiCodes: '',
      openNumbersInput: false,
      showUploadError: false,
      IsCheckRepet: true,
      uploadTitle: '',
      uploadUrl: '',
      templateUrl: 'http://wms.xingyunyi.cn/Data/Template/索赔清单.xlsx',
      fileList: [],
      errorMsgs: [],
      uploading: false,
      openUploadPannel: false,
      loading: false,
      submiting: false,
      selectedItems: [],
      editMode: '',
      users: [],
      customers: [],
      channels: [],
      claimTime: null,
      CodeTypes: [
        { Name: '中转单号', Id: 1 },
        { Name: '跟踪号', Id: 2 },
        { Name: '客户单号', Id: 3 }
      ],
      claimStatus: [
        { Name: '未索赔', Id: 0 },
        { Name: '已索赔', Id: 1 }
      ],
      editItem: {},
      rules: {
        CustomerCnName: {
          required: true,
          message: '请填写客户品名',
          trigger: 'blur'
        },
        DeclarationOfChineseName: {
          required: true,
          message: '请填写报关品名',
          trigger: 'blur'
        },
        DeclarationOfEnglishName: {
          required: true,
          message: '请填写报关英文品名',
          trigger: 'blur'
        },

        Type: { required: true, message: '请选择类型', trigger: 'blur' },
        OperationNode: {
          required: true,
          message: '请选择作用节点',
          trigger: 'blur'
        }
      },
      sourceData: [],
      pagerDto: {
        _Eq_CreateUserName: null,
        _Eq_CodeType: null,
        _In_Codes: '',
        _Eq_ChannelId: null,
        _LeE_ClaimTime: null,
        _GrE_ClaimTime: null,
        _Range_CreateTime:null,
        _Eq_IsInterceptCustomers:'',
        PageIndex: 1,
        PageSize: 100,
        total: 0
      },
      checkVisible: false, // 审核弹窗
      auditCheck: false,
      editCheckData: [],
      validRules: {
        AuditTotalAmount: [{ required: true, message: '请输入赔付金额' }]
      },
      mergeCellsCheckData: {},
      rowNum: 0,
      colNum: 0,
    }
  },
  filters: {
    getTotalAmount(row, tableList) {
      if (tableList.length > 0) {
        const filterList = tableList.filter(item => item.CustomerName == row.CustomerName && !item.TotalAmount)
        const totalSum = filterList.reduce((acc, item) => acc + Number(item.AuditTotalAmount), 0);
        return floorToDecimals(totalSum, 2)
      }
      return row.TotalAmount
    }
  },
  computed: {
    headers() {
      const token = getToken()
      return {
        token: token
      }
    },
    getMergeCells() {
      const mergeCellsCheckData = this.mergeCellsCheckData
      if (Object.keys(mergeCellsCheckData).length === 0) return [{ row: 0, col: 0, rowspan: 0 }]
      const mergeCells = []
      this.rowNum = 0
      this.colNum = 0
      Object.values(mergeCellsCheckData).forEach(item => {
        this.colNum += item.length
        mergeCells.push({ row: this.rowNum, col: 0, rowspan: item.length - 1 })
        mergeCells.push({ row: this.colNum - 1, col: 0, colspan: 14 })
        this.rowNum += item.length
      })
      return mergeCells
      // { row: 5, col: 0, rowspan: 2 }
    }
  },
  created() {
    _getDeliverChannel().then((resp) => {
      this.channels = resp
    })
    _getAllUsers().then((resp) => {
      this.users = resp
    })
    _getCustomers().then((resp) => {
      this.customers = resp
    })
    this.pagerDto.PageIndex = 1
    this.pagerDto._Eq_ChannelId = ''
    this.searchData()
  },
  methods: {
    colFormatDate,
    downClaimRecords() {
      this.downloading = true
      var url = `${process.env.VUE_APP_BASE_API}/ClaimRecord/Down`
      var x = new XMLHttpRequest()
      x.open('POST', url, true)
      x.responseType = 'blob'
      x.setRequestHeader('content-type', 'application/json')
      x.setRequestHeader('token', getToken())

      x.onload = (e) => {
        this.downloading = false
        var url = window.URL.createObjectURL(x.response)
        var a = document.createElement('a')
        a.href = url
        a.download = `导出索赔记录.xls`
        a.click()
        this.downloadLoading = false
      }
      const data = JSON.stringify(this.pagerDto)
      x.send(data)
    },
    openNumbersInputPannel() {
      const str = format(this.pagerDto._In_Codes, '\n')
      this.inputMultiCodes = str
      this.openNumbersInput = true
    },
    confirmMultiCodes() {
      const inputs = this.inputMultiCodes
      const str = format(inputs, ',')
      this.pagerDto._In_Codes = str
      this.inputMultiCodes = ''
      this.openNumbersInput = false
    },
    errorDialogClosed() {
      this.errorMsgs = []
    },
    uploadClosed() {
      this.$refs.upload.clearFiles()
    },
    openUploadClaim() {
      this.uploadTitle = '导入未索赔记录'
      this.uploadUrl = `${process.env.VUE_APP_BASE_API}/ClaimRecord/UploadClaim?IsCheckRepet=${this.IsCheckRepet}`
      this.openUploadPannel = true
    },
    IsCheckRepetChange() {
      this.uploadUrl = `${process.env.VUE_APP_BASE_API}/ClaimRecord/UploadClaim?IsCheckRepet=${this.IsCheckRepet}`
    },
    uploadSuccess(response, file, fileList) {
      const data = response.Data
      if (!!data && data.length > 0) {
        this.errorMsgs = data
        this.showUploadError = true
      } else {
        this.$message({
          message: '导入成功',
          type: 'success'
        })
        this.searchData()
      }
      this.openUploadPannel = false
      this.uploading = false
    },
    uploadError(err, file, fileList) {
      this.$message({
        message: err.message,
        type: 'error'
      })
      this.openUploadPannel = false

      this.uploading = false
    },
    submitUpload() {
      this.uploading = true
      // this.saveLodding=true
      this.$refs.upload.submit()
    },
    openUpload() {
      this.openUploadPannel = true
    },
    ClaimTimeSeleted(dateRange) {
      if (dateRange.length > 0) {
        this.pagerDto._GrE_CreateTime = dateRange[0]
        this.pagerDto._LeE_CreateTime = dateRange[1]
      } else {
        this.pagerDto._GrE_CreateTime = ''
        this.pagerDto._LeE_CreateTime = ''
      }
    },
    changeDepartment() {
      if (!this.selectedItems || this.selectedItems.length == 0) {
        this.$message({ message: '请先勾选要变更责任部门的项', type: 'error' })
      } else {
        this.$prompt('变更责任部门为', '变更').then(({ value }) => {
          const ids = this.selectedItems.map((i) => i.Id)
          request({
            url: '/ClaimRecord/ChangeDepartment',
            method: 'post',
            data: { ids: ids, department: value }
          })
            .then((resp) => {
              if (resp.success === true) {
                this.$message({ message: '变更成功', type: 'success' })
                this.searchData()
              } else {
                const msg = resp.message
                this.$message({ message: msg, type: 'error' })
              }
            })
            .finally(() => {})
        })
      }
    },
    batchDelete() {
      if (!this.selectedItems || this.selectedItems.length == 0) {
        this.$message({ message: '请先勾选要删除的项', type: 'error' })
      } else {
        this.$confirm('是否删除勾选项', '正在操作', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          const ids = this.selectedItems.map((i) => i.Id)
          request({
            url: '/ClaimRecord/BatchDelete',
            method: 'post',
            data: ids
          })
            .then((resp) => {
              if (resp.success === true) {
                this.$message({ message: '删除成功', type: 'success' })
                this.searchData()
              } else {
                const msg = resp.message
                this.$message({ message: msg, type: 'error' })
              }
            })
            .finally(() => {})
        })
      }
    },
    handleSelectionChange(val) {
      this.selectedItems = val
    },
    searchData() {
      this.loading = true
      request({
        url: '/ClaimRecord/query',
        method: 'post',
        data: this.pagerDto
      })
        .then((resp) => {
          this.loading = false
          this.pagerDto.total = resp.TotalCount
          this.pagerDto.PageIndex = resp.PageIndex

          this.sourceData = resp.Result
        })
        .finally(() => {
          this.loading = false
        })
    },
    remove(item) {
      this.$confirm('是否删除该索赔记录?', '正在删除', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.loading = true
        request({
          url: '/ClaimRecord/Delete',
          params: { id: item.Id },
          method: 'post'
        })
          .then((resp) => {
            if (resp.success === true) {
              this.$message({ message: '删除成功', type: 'success' })
              const idx = this.sourceData.findIndex((i) => i.Id === item.Id)
              this.sourceData.splice(idx, 1)
            } else {
              const msg = resp.message
              this.$message({ message: msg, type: 'error' })
            }
          })
          .catch(() => {
            this.$message({ message: '删除出错', type: 'error' })
          })
          .finally(() => {
            this.loading = false
          })
      })
    },
    pagerSerach(p) {
      this.pagerDto.PageIndex = p
      this.searchData()
    },
    // 审核弹窗
    handleCheckDialog(type, row) {
      switch (type) {
        // 单个
        case 'single':
          if (!row) return
          this.editCheckData = [row].map(item => {
            if (!item.AuditCost) item.AuditCost = item.Cost
            if (!item.AuditFreight) item.AuditFreight = item.Freight
            if (!item.AuditTotalValue) item.AuditTotalValue = item.TotalValue
            if (!item.AuditSolution) item.AuditSolution = item.SolutionName
            return item
          })
          break
        // 批量
        case 'batch':
          if (!this.selectedItems || this.selectedItems.length == 0) {
            this.$message({ message: '请先勾选未索赔的数据', type: 'error' })
            return
          }
          if (this.selectedItems.some(item => item.ClaimStatus !== 0)) {
            this.$message({ message: '请先勾选未索赔的数据', type: 'error' })
            return
          }
          const editCheckData = [...this.selectedItems].map(item => {
            if (!item.AuditCost) item.AuditCost = item.Cost
            if (!item.AuditFreight) item.AuditFreight = item.Freight
            if (!item.AuditTotalValue) item.AuditTotalValue = item.TotalValue
            if (!item.AuditSolution) item.AuditSolution = item.SolutionName
            if (!item.AuditTotalAmount) item.AuditTotalAmount = floorToDecimals((item.Cost + item.Freight), 2)
            return item
          })
          const targetData = editCheckData.reduce((result, item) => {
            const key = item.CustomerName;
            if (!result[key]) {
              result[key] = [];
            }
            result[key].push(item);
            return result;
          }, {});
          Object.keys(targetData).forEach(city => {
            if (city) {
              const totalSum = targetData[city].reduce((acc, item) => acc + item.AuditTotalAmount, 0);
              const TotalAmount = floorToDecimals(totalSum, 2)
              targetData[city].push({
                IsFilter: true,
                TotalAmount,
                AuditTotalAmount: TotalAmount,
                CustomerName: targetData[city][0]['CustomerName']
              })
            }
          });
          this.mergeCellsCheckData = targetData
          this.editCheckData = Object.values(targetData).flat()
          break
      }
      this.checkVisible = true
    },
    handleCheckClose() {
      this.auditCheck = false
      this.checkVisible = false
      this.editCheckData = []
      this.mergeCellsCheckData = {}
    },
    // 审核
    async hanleAudit() {
      const $table = this.$refs.checkRef
      const errMap = await $table.fullValidate(true)
      if (errMap) {
        const msgList = []
        Object.values(errMap).forEach(errList => {
          errList.forEach(params => {
            const { rowIndex, column, rules } = params
            rules.forEach(rule => {
              msgList.push(`第 ${rowIndex + 1} 行 ${column.title} 校验错误：${rule.message}`)
            })
          })
        })
        VXETable.modal.message({
          status: 'error',
          slots: {
            default() {
              return [
                <div class='red' style='max-height: 400px;overflow: auto;'>
                  {
                    msgList.map(msg => <div>{ msg }</div>)
                  }
                </div>
              ]
            }
          }
        })
      } else {
        // const data = [...this.editCheckData]
        const data = [...this.editCheckData].filter(item => !item.IsFilter)
        this.auditCheck = true
        request({
          url: '/ClaimRecord/PassClaimRecords',
          method: 'post',
          data
        })
          .then((resp) => {
            if (resp.success === true) {
              this.$message({ message: '审核成功', type: 'success' })
              this.checkVisible = false
              this.searchData()
            } else {
              const msg = resp.message
              this.$message({ message: msg, type: 'error' })
            }
          })
          .finally(() => {
            this.auditCheck = false
          })
      }
    },
    // 更新校验状态
    updateTableStatus(scope) {
      this.$refs.checkRef.updateStatus(scope)
    },
    rowClassName ({ row }) {
      if (row.TotalAmount) return 'fee-total-amount'
      return null
    },
    changeAuditTotalAmount(scope) {
      const totalSum = Number(scope.row.AuditCost) + Number(scope.row.AuditFreight)
      scope.row.AuditTotalAmount = floorToDecimals(totalSum, 2)
    }
  }
}
</script>
<style>
.total-amount-warp {
  display: flex;
  justify-content: space-between;
}
.fee-total-amount {
  font-size: 16px;
  font-weight: bold;
  color: #FF2442;
}
.table-warp .define-button + .el-button {
  margin-left: 0;
  margin-top: 6px;
}
.check-visible .define-cell-bg {
  background-color: #e6f7ff;
}
.check-visible .amount-cell-bg {
  background-color: #e7faf0;
}
.check-visible .vxe-cell {
  padding-left: 6px;
  padding-right: 6px;
}
.check-visible .audit-textarea .el-textarea__inner {
  padding: 5px;
}

.check-visible .audit-textarea .el-textarea__inner::-webkit-scrollbar {
    width: 6px;
    /* 滚动条宽度， width：对应竖滚动条的宽度  height：对应横滚动条的高度*/
    height: 8px;
    background: #eee;
}

/*定义滚动条轨道（凹槽）样式*/
.check-visible .audit-textarea .el-textarea__inner::-webkit-scrollbar-track {
  -webkit-box-shadow: inset 0 0 6px rgba(0, 0, 0, 0.3);
  /* 较少使用 */
  border-radius: 3px;
  background: rgba(0, 0, 0, 0.1);
}

/*定义滑块 样式*/
.check-visible .audit-textarea .el-textarea__inner::-webkit-scrollbar-thumb {
  border-radius: 3px;
  height: 100px;
  /* 滚动条滑块长度 */
  -webkit-box-shadow: inset 0 0 5px rgba(0, 0, 0, 0.2);
  background: rgba(0, 0, 0, 0.2);
}
</style>
