<template>
  <div class="page-container column-container">
    <div
      style="position: absolute;  top: 0;  bottom: 0;  left: 0;  right: 0;z-index: 10; background-color: rgba(255, 255, 255, 0.5);"
      v-if="showMask"></div>
    <el-form class="list-search-container" :model="queryParams" ref="queryRef" :inline="true">
      <el-form-item label="结算日期：">
        <el-date-picker v-model="queryParams.checkoutDate" type="date" value-format="YYYY-MM-DD" :clearable="true"
          placeholder="结算日期" style="width: 130px" @change="handleDateChange" />
      </el-form-item>
      <el-form-item label="结束日期：">
        <el-date-picker v-model="queryParams.endDate" type="date" value-format="YYYY-MM-DD" :clearable="true"
          placeholder="结束日期" style="width: 130px" :disabled-date="(arg) => disabledDateHandler(arg, 'endDate')" />
      </el-form-item>
      <el-form-item label="结算月：">
        <el-date-picker v-model="form.checkMonth" type="month" value-format="YYYY-MM-01" format="YYYY年MM月"
          :clearable="true" placeholder="结算月" style="width: 130px" readonly />
      </el-form-item>
      <el-form-item label="外协单位：">
        <el-input v-model.trim="queryParams.supplierName" placeholder="外协单位" style="width: 130px" />
      </el-form-item>
      <el-form-item label="结算状态：">
        <el-select v-model="queryParams.status" placeholder="结算状态" style="width: 130px">
          <el-option v-for="dict in outsource_checkout_status" :key="dict.value" :label="dict.label"
            :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="info" icon="Search" @click="handleQuery">搜索</el-button>
      </el-form-item>
    </el-form>
    <!-- 功能按钮区 -->
    <div class="list-btns-container">
      <!-- <el-button type="primary" icon="DocumentChecked" @click="handleSave"
        v-hasPermi="['business:balanceAccount:save']">
        保存
      </el-button> -->
      <el-button type="success" icon="Plus" @click="handleBalance" v-hasPermi="['business:balanceAccount:confirm']">
        结算
      </el-button>
      <el-button type="primary" icon="Select" @click="handleCheckAll">
        全选
      </el-button>
      <el-button type="info" icon="Close" @click="handleDisbalance" v-hasPermi="['business:balanceAccount:cancel']">
        取消结算
      </el-button>
      <el-button type="warning" icon="Download" @click="handleExport" v-hasPermi="['business:balanceAccount:export']">
        导出
      </el-button>
    </div>
    <!-- 渲染数据区 -->
    <div class="el-table-container" style="flex-basis: 1;">
      <div class="el-table-inner-container">
        <vxe-table ref="tableRef" border height="100%" :loading="loading" size="small" :row-config="{ isHover: true }"
          :data="tableData" :checkbox-config="{ highlight: true }" :scroll-y="{ enabled: true }" show-overflow
          :column-config="{ resizable: true }" keep-source :filter-config="{ showIcon: false }"
          :edit-config="{ trigger: 'click', mode: 'row', showStatus: true, beforeEditMethod: beforeEditCheck, showIcon: false }"
          @checkbox-change="handleSelectChange" @checkbox-all="handleCheckAllChange" @edit-closed="handleEditClosed"
          class="X-scrollbar Y-scrollbar">
          <vxe-column type="checkbox" width="50" align="center"></vxe-column>
          <vxe-column field="supplierName" title="外协商简称" align="center" width="110">
          </vxe-column>
          <vxe-column field="outsourceNo" title="发出单号" align="center" width="120">
          </vxe-column>
          <vxe-column field="lotCode" title="批次号" align="center" width="120">
          </vxe-column>
          <vxe-column field="productDescription" title="产品描述" align="center" width="220">
          </vxe-column>
          <vxe-column field="processAlias" title="工序名称" align="center" width="100">
          </vxe-column>
          <vxe-column field="status" title="状态" align="center" width="100">
            <template #default="scope">
              <div>{{ scope.row.status === 0 ? '已审核' : '已结算' }}</div>
            </template>
          </vxe-column>
          <vxe-colgroup title="工序单价" align="center">
            <template #header="scope">
              <div><el-icon>
                  <Edit />
                </el-icon>工序单价</div>
            </template>
            <vxe-column field="processPrice" align="center" :filters="processOptions" :edit-render="{}"
              :filter-method="processPriceFilterMethod" width="100">
              <template #header="{ column }">
                <vxe-select v-for="(option, index) in column.filters" :key="index" v-model="option.data"
                  :options="priceFilterList" @change="confirmFilterEvent(option)" placeholder="请选择" transfer
                  style="width: 100%;"></vxe-select>
              </template>
              <template #edit="scope">
                <el-input-number v-model="scope.row.processPrice" :controls="false" :min="0" :precision="4"
                  style="width: 100%;" @blur="handleBlur(scope.row)" />
              </template>
            </vxe-column>
          </vxe-colgroup>
          <!-- <vxe-column field="processPrice" title="工序单价" align="center" :edit-render="{}" width="100">
            <template #edit="scope">
              <el-input-number v-model="scope.row.processPrice" :controls="false" :min="0" :precision="4"
                style="width: 100%;" @blur="handleBlur(scope.row)" />
            </template>
          </vxe-column> -->
          <vxe-column field="otherCost" title="其他扣款" align="center" :edit-render="{}" width="100">
            <template #header="scope">
              <div><el-icon>
                  <Edit />
                </el-icon>其他扣款</div>
            </template>
            <template #edit="scope">
              <el-input-number v-model="scope.row.otherCost" :controls="false" :min="0" :precision="4"
                style="width: 100%;" @blur="handleBlur(scope.row)" />
            </template>
          </vxe-column>
          <vxe-column field="fillDifferencePrice" title="差补额" align="center" :edit-render="{}" width="100">
            <template #header="scope">
              <div><el-icon>
                  <Edit />
                </el-icon>补差额</div>
            </template>
            <template #edit="scope">
              <el-input-number v-model="scope.row.fillDifferencePrice" :controls="false" :min="0" :precision="4"
                style="width: 100%;" @blur="handleBlur(scope.row)" />
            </template>
          </vxe-column>
          <vxe-column field="productNum" title="投入数量" align="center" width="100">
          </vxe-column>
          <vxe-column field="outputNum" title="发出数量" align="center" width="100">
          </vxe-column>
          <vxe-column field="receiptNum" title="收回数量" align="center" width="100">
          </vxe-column>
          <vxe-colgroup title="实投料量" align="center">
            <vxe-column field="actualInventory" :filters="InventoryOptions" align="center"
              :filter-method="actualInventoryFilterMethod" width="100">
              <template #header="{ column }">
                <vxe-select v-for="(option, index) in column.filters" :key="index" v-model="option.data"
                  :options="actualInventoryList" @change="confirmFilterEvent(option)" placeholder="请选择" transfer
                  style="width: 100%;"></vxe-select>
              </template>
            </vxe-column>
          </vxe-colgroup>
          <!-- <vxe-column field="actualInventory" title="实投料量" align="center" width="100">
          </vxe-column> -->
          <vxe-column field="materialLoss" title="料损数量" align="center" width="100">
          </vxe-column>
          <vxe-column field="materialLossAmount" title="扣料金额" align="center" width="100">
          </vxe-column>
          <vxe-column field="planAmount" title="应得金额" align="center" width="100">
          </vxe-column>
          <vxe-column field="acutalAmount" title="实得金额" align="center" width="100">
          </vxe-column>
          <vxe-column field="taxAmount" title="含税金额" align="center" width="100">
          </vxe-column>
          <vxe-column field="freightAmount" title="运费" align="center" width="100">
          </vxe-column>
          <vxe-column field="materialPrice" title="材料单价" align="center" width="100">
          </vxe-column>
          <vxe-column field="salePrice" title="销售单价" align="center" width="100">
          </vxe-column>
          <vxe-column field="wastePrice" title="废品单价" align="center" width="100">
          </vxe-column>
          <vxe-column field="carrierNum" title="箱数" align="center" width="100">
          </vxe-column>
          <!-- 该序号是工序的的序号 -->
          <vxe-column field="processSort" title="序号" align="center" width="100">
          </vxe-column>
          <vxe-column field="processCode" title="工序代码" align="center" width="100">
          </vxe-column>
          <vxe-column field="checkoutDate" title="结算日期" align="center" width="100">
          </vxe-column>
          <vxe-column field="auditDate" title="审核日期" align="center" width="100">
          </vxe-column>
          <vxe-column field="returnDate" title="收回日期" align="center" width="100">
          </vxe-column>
          <vxe-column field="returnNo" title="收回单号" align="center" width="120">
          </vxe-column>
          <vxe-column field="settlementType" title="结算方式" align="center" width="100">
          </vxe-column>
          <vxe-column field="furnaceNum" title="炉数" align="center" width="100">
          </vxe-column>
          <vxe-column field="checkDate" title="检查日期" align="center" width="100">
          </vxe-column>
          <vxe-column field="supplierCode" title="外协单位码" align="center" width="100">
          </vxe-column>
          <vxe-column field="inspectionNo" title="检查单号" align="center" width="130">
          </vxe-column>
          <vxe-column field="productCode" title="产品编码" align="center" width="100">
          </vxe-column>
          <vxe-column field="materialLossRatio" title="料损率" align="center" width="100">
          </vxe-column>
          <vxe-column field="surfaceTreatment" title="表面" align="center" width="100">
          </vxe-column>
          <vxe-column field="length" title="长度" align="center" width="100">
          </vxe-column>
          <vxe-column field="materialDiameter" title="材料直径" align="center" width="100">
          </vxe-column>
          <vxe-column field="tolerance" title="公差" align="center" width="100">
          </vxe-column>
          <vxe-column field="utilizationRatio" title="利用率" align="center" width="100">
          </vxe-column>
          <vxe-column field="currency" title="币别" align="center" width="100">
          </vxe-column>
          <vxe-column field="taxRate" title="税率" align="center" width="100">
          </vxe-column>
          <vxe-column field="year" title="结算年" align="center" width="100">
          </vxe-column>
          <vxe-column field="month" title="结算月" align="center" width="100">
          </vxe-column>
          <vxe-column field="wastePriceCategory" title="废品价类别" align="center" width="100">
          </vxe-column>
          <vxe-column field="rawMaterialCode" title="材料编码" align="center" width="140">
          </vxe-column>
          <vxe-column field="density" title="密度" align="center" width="100">
          </vxe-column>
          <vxe-column field="shape" title="形状" align="center" width="100">
          </vxe-column>
          <vxe-column field="type" title="类别" align="center" width="100">
          </vxe-column>
        </vxe-table>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref } from 'vue'
// import region from '@/utils/region.js'
import { listBalanceAccount, checkout, discheckout, saveBatchBalanceAccount, updateBalanceAccount, exportBalanceAccount } from '@/api/business/outsourceBalanceAccount'
import { listOutsourceBalanceMonth } from '@/api/business/outsourceBalanceMonth.js'
const { proxy } = getCurrentInstance();
const tableData = ref([])
const tableRef = ref(null)
const selected = ref([])
const loading = ref(false)
const total = ref(0)
let rows = []
const form = ref({
  checkMonth: null
})
const processOptions = ref([{
  data: ''
}])
const InventoryOptions = ref([{
  data: ''
}])
const priceFilterList = ref([
  { label: '全部', value: '' },
  { label: '有价', value: '1' },
  { label: '无价', value: '0' }
])
const actualInventoryList = ref([
  { label: '全部', value: '' },
  { label: '大于0', value: '1' },
  { label: '小于等于0', value: '0' }
])
const showMask = ref(true)
const balanceMonth = ref(null)

// const { outsource_checkout_status } = proxy.useDict("outsource_checkout_status");
const outsource_checkout_status = ref([{
  label: '全部', value: ''
}, {
  label: '已审核', value: 0
}, {
  label: '已结算', value: 1
}])

const queryParams = ref({
  pageSize: 5000,
  pageNum: 0
})
const checkBalanceAccount = () => {
  // 判断是否有结算月，假设未设置则显示遮罩层
  listOutsourceBalanceMonth({}).then(res => {
    if (res.rows.length == 0) {
      proxy.$modal.msgError('未进设置外协月结期间不能进行结算')
      showMask.value = true
    } else {
      balanceMonth.value = res.rows[0]
      showMask.value = false
    }
    // showMask.value = true
  }).catch(_ => {
  })
}
const getList = () => {
  listBalanceAccount(queryParams.value).then(res => {
    tableData.value = res.rows
    total.value = res.total
  })
}
const getListAll = () => {
  // 每次查500条，直到查齐
  queryParams.value.pageNum++
  listBalanceAccount(queryParams.value).then(res => {
    rows.push(...res.rows)
    total.value = res.total
    if (rows.length < total.value) {
      getListAll()
    } else {
      tableData.value.push(...rows)
      loading.value = false
    }
  })
}
const handleQuery = () => {
  // 判断假设没有结算日期则提示选择结算日期
  if (queryParams.value.checkoutDate == null) {
    proxy.$modal.msgError('请选择结算日期')
    return
  }
  queryParams.value.pageNum = 0
  tableData.value = []
  rows = []
  loading.value = true
  getListAll()
}
const changeCellEvent = (params) => {
  const $table = tableRef.value
  if ($table) {
    $table.updateStatus(params)
  }
  // console.log(tableData.value)
}

const handleBalance = () => {
  selected.value = tableRef.value.getCheckboxRecords(true)
  if (proxy.moment(queryParams.value.checkoutDate).isBefore(balanceMonth.value.startDate)) {
    proxy.$modal.msgError('结算日期不能小于结算期间')
    return
  }
  if (proxy.moment(queryParams.value.checkoutDate).isAfter(balanceMonth.value.endDate)) {
    proxy.$modal.msgError('结算日期不能大于结算期间')
    return
  }
  if (selected.value.length == 0) {
    proxy.$modal.msgError('请选择结算单')
    return
  }
  if (form.value.checkMonth == null) {
    proxy.$modal.msgError('请选择结算月份')
    return
  }
  // 判断已选择结算单是否已经结算，已经结算则不能再次结算。
  if (selected.value.some(e => e.status == 1)) {
    proxy.$modal.msgError('选中结算单存在已结算')
    return
  }
  selected.value.forEach(item => {
    item.year = proxy.moment(form.value.checkMonth).format('YYYY')
    item.month = proxy.moment(form.value.checkMonth).format('MM')
    item.checkoutDate = queryParams.value.checkoutDate
  })
  checkout(selected.value).then(res => {
    proxy.$modal.msgSuccess('结算成功')
    handleQuery()
  })
}

const handleDisbalance = () => {
  selected.value = tableRef.value.getCheckboxRecords(true)
  if (selected.value.length == 0) {
    proxy.$modal.msgError('请选择要取消的结算单')
    return
  }
  selected.value.forEach(item => {
    item.year = ''
    item.month = ''
  })
  // console.log(selected.value.length)
  if (selected.value.length > 100) {
    proxy.$modal.msgError('一次只能操作100条数据')
    return
  }
  discheckout(selected.value).then(res => {
    proxy.$modal.msgSuccess('取消结算成功')
    handleQuery()
  })
}

const handleCheckAll = () => {
  const $table = tableRef.value
  if ($table) {
    $table.setAllCheckboxRow(true)
    selected.value = $table.getCheckboxRecords(true)
    // console.log(selected.value)
  }
}

const handleExport = () => {
  // const $table = tableRef.value
  // if ($table) {
  //   $table.exportData({
  //     type: 'xlsx',
  //     filename: '外协结算信息'
  //   })
  // }
  if (queryParams.value.checkoutDate == null) {
    proxy.$modal.msgError('请选择结算日期')
    return
  }
  exportBalanceAccount({ ...queryParams.value, status: 1 })
}

const handleSelectChange = ({ checked, row, rowIndex, records }) => {
  // console.log('select-one: ', checked, records, row, rowIndex)
  // selected.value = records
  // 判断选中的是否是按炉结算假设是按炉结算则同时选中该炉的所有批次
  const $table = tableRef.value
  if (row.settlementType == 2 && $table != null) {
    // console.log(row.outsourceOrderId)
    const selects = tableData.value.filter(e => e.outsourceOrderId == row.outsourceOrderId)
    // console.log(selects.length)
    $table.setCheckboxRow(selects, checked)
    selected.value = $table.getCheckboxRecords(true)
    // console.log(selected.value.length)
  }
}
const handleCheckAllChange = ({ checked, records }) => {
  // console.log('select-all', checked, records)
  selected.value = records
}

const handleDateChange = (arg) => {
  // 获取结算日期的月份自动填入结算月
  form.value.checkMonth = proxy.moment(arg).format('YYYY-MM-01')
  // console.log(arg)
  // console.log(form.value.checkMonth)
}

const disabledDateHandler = (date, type) => {
  if (type === 'endDate') {
    // console.log(queryParams.value.checkoutDate)
    // console.log(proxy.moment(date).format('MM'), proxy.moment(queryParams.value.checkoutDate).format('MM'))
    if (queryParams.value.checkoutDate == null || proxy.moment(date).format('MM') != proxy.moment(queryParams.value.checkoutDate).format('MM')) return true
    else return false
  }
}

const handleSave = () => {
  const params = tableRef.value.getUpdateRecords()
  // console.log(params)
  saveBatchBalanceAccount(params).then(res => {
    proxy.$modal.msgSuccess('保存成功')
    handleQuery()
  })
}

const beforeEditCheck = ({ row }) => {
  // 判断当结算月小于当前结算期开始日期时不能编辑
  if (row.checkoutDate != null && proxy.moment(row.checkoutDate).isBefore(balanceMonth.value.startDate)) {
    return false
  }
  return true
}
const handleBlur = (params) => {
  // console.log(params)
  // 计算应收金额，实收金额
  let planAmount = 0
  let acutalAmount = 0
  let taxAmount = 0
  if (params.settlementType == 1) {
    if (params.surfaceTreatment == 'N') {
      // 没有表面处理
      if (params.supplierCode == '99024' && params.processCode != '99000') {
        // console.log(params.processCode)
        planAmount = (params.outputNum * params.processPrice * (1 + params.taxRate / 100)).toFixed(4)
      } else {
        // console.log(params.processCode)
        planAmount = (params.receiptNum * params.processPrice * (1 + params.taxRate / 100)).toFixed(4)
      }
    } else {
      // 有表面处理
      if (params.supplierCode == '99024') {
        planAmount = (params.outputNum * params.processPrice * (1 + params.taxRate / 100)).toFixed(4)
      } else {
        planAmount = (params.receiptNum * params.processPrice * (1 + params.taxRate / 100)).toFixed(4)
      }
    }
  } else {
    planAmount = (1 * params.processPrice * (1 + params.taxRate / 100)).toFixed(4)
  }
  if (params.surfaceTreatment == 'N') {
    if (params.wastePriceCategory == '24') {
      params.wastePrice = params.processPrice
      params.materialLossAmount = (params.materialLoss * params.wastePrice * (1 + params.taxRate / 100)).toFixed(4)
    }
  } else {
    if (params.wastePriceCategory == '22') {
      params.wastePrice = (params.processPrice * 2).toFixed(4)
      params.materialLossAmount = (params.materialLoss * params.wastePrice * (1 + params.taxRate / 100)).toFixed(4)
    }
    if (params.wastePriceCategory == '23') {
      params.wastePrice = (params.processPrice * 3).toFixed(4)
      params.materialLossAmount = (params.materialLoss * params.wastePrice * (1 + params.taxRate / 100)).toFixed(4)
    }
  }
  taxAmount = (planAmount - params.otherCost + params.fillDifferencePrice - params.freightAmount - params.materialLossAmount).toFixed(4)
  acutalAmount = ((planAmount - params.otherCost + params.fillDifferencePrice - params.freightAmount - params.materialLossAmount) / (1 + params.taxRate / 100)).toFixed(4)
  params.planAmount = planAmount
  params.acutalAmount = acutalAmount
  params.taxAmount = taxAmount
}

const saveRow = (row) => {
  updateBalanceAccount(row).then(res => {
    const $table = tableRef.value
    if (res.code === 200) {
      // proxy.$modal.msgSuccess('保存成功')
      if ($table != null) {
        $table.reloadRow(row, res.data)
      }
    } else {
      proxy.$modal.msgError(res.msg)
    }
  })
}

const processPriceFilterMethod = ({ option, row, column }) => {
  if (option.data != '') {
    return option.data == '0' ? row[column.field] <= 0 : row[column.field] > 0
  }
  return true
}
const actualInventoryFilterMethod = ({ option, row, column }) => {
  if (option.data != '') {
    return option.data == '0' ? row[column.field] <= 0 : row[column.field] > 0
  }
  return true
}
const confirmFilterEvent = (option) => {
  const $table = tableRef.value
  if ($table) {
    // 设置为选中状态
    option.checked = true
    // 修改条件之后，需要手动调用 updateData 处理表格数据
    $table.updateData()
  }
}
const handleEditClosed = (params) => {
  // console.log(params)
  const { row, column } = params
  const field = column.field
  // 判断是否真有需要保存的部分

  const updates = tableRef.value.getUpdateRecords()
  console.log(updates)
  if (updates.length > 0) {
    saveRow(row)
  }
}
// const handleScroll = (params) => {
//   // console.log('scroll')
//   if (params.scrollTop + params.bodyHeight >= params.scrollHeight) {
//     console.log('已经到底部了')
//   }
// }
checkBalanceAccount()
// getList()
</script>
<style>
.vxe-table--scrollbar-y .body--scrollbar-y .scrollbar-wrap::-webkit-scrollbar {
  width: 10px;
  /* 滚动条宽度 */
  height: 10px;
  /* 滚动条高度 */
}

.vxe-table--scrollbar-x .body--scrollbar-x .scrollbar-wrap::-webkit-scrollbar {
  width: 10px;
  /* 滚动条宽度 */
  height: 10px;
  /* 滚动条高度 */
}
</style>