<template>
  <div class="app-container">
    <el-form :model="queryParamsCost" ref="queryCostRef" :inline="true" label-width="100px">
      <el-form-item label="运单号" prop="externalWaybillNo">
        <el-input
            v-model="queryParamsCost.externalWaybillNo"
            placeholder="请输入运单号"
            clearable
            @keyup.enter="handleQueryCost"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQueryCost">搜索</el-button>
        <el-button icon="Refresh" @click="resetQueryCost">重置</el-button>
      </el-form-item>
    </el-form>
    <el-table v-loading="loadingCost" :data="monthSummaryListCost">
      <!--      <el-table-column label="序号" align="center" type="index"></el-table-column>-->
      <el-table-column label="日期" align="center" prop="signTime" show-overflow-tooltip />
      <el-table-column label="运单号码" align="center" prop="externalWaybillNo" show-overflow-tooltip />
      <el-table-column label="寄件地区" align="center" prop="senderCity" />
      <el-table-column label="到件地区" align="center" prop="receiverCity" />
      <el-table-column label="计费重量" align="center" prop="goodsWeight" />
      <el-table-column label="产品类型" align="center"  >
        <template #default="scope">
          <span v-if="scope.row.orderType == 1">{{formatterOptions(jd_logistics_product_code,scope.row.productCode)}}</span>
          <span v-if="scope.row.orderType == 2">{{formatterOptions(sf_logistics_product_code,scope.row.productCode)}}</span>
        </template>
      </el-table-column>
      <el-table-column label="付款方式" align="center"  >
        <template #default="scope">
          <span>月结</span>
        </template>
      </el-table-column>
      <el-table-column label="费用（元）" align="center" prop="rateAmount" />aaaaa
      <!--      <el-table-column label="经手人" align="center" prop="userName" />-->
      <el-table-column label="增值费用" align="center" prop="feeItemName" />
      <!--      <el-table-column label="备注" align="center" prop="remark" show-overflow-tooltip/>-->
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" fixed="right" width="100" v-if="routeQuery.status == 1">
        <template #default="scope">
          <el-button type="text" @click="handleUpdate(scope.row)" v-hasPermi="['system:costDetails:edit']" >调账</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
        v-show="totalCost>0"
        :total="totalCost"
        v-model:page="queryParamsCost.pageNum"
        v-model:limit="queryParamsCost.pageSize"
        @pagination="getCostDetailsList"
    />
    <!-- 添加或修改财务月度汇总对话框 -->
    <el-dialog title="调账" v-model="open" width="70%" append-to-body>
      <el-form ref="costListRef" :model="form" :rules="rules" label-width="160px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="日期" prop="signTime">
              <el-input v-model="form.signTime" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="运单号码" prop="externalWaybillNo">
              <el-input v-model="form.externalWaybillNo" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="寄件地区" prop="senderCity">
              <el-input v-model="form.senderCity" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="到件地区" prop="receiverCity">
              <el-input v-model="form.receiverCity" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="计费重量" prop="goodsWeight">
              <el-input v-model="form.goodsWeight" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="产品类型" prop="goodsType">
              <el-input v-model="form.goodsType" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="付款方式" prop="payType">
              <el-input v-model="form.payType" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="费用（元）" prop="rateAmount">
              <el-input v-model="form.rateAmount" disabled />
            </el-form-item>
          </el-col>
          <!--          <el-col :span="12">-->
          <!--            <el-form-item label="经手人" prop="userName">-->
          <!--              <el-input v-model="form.userName" disabled />-->
          <!--            </el-form-item>-->
          <!--          </el-col>-->
          <el-col :span="12">
            <el-form-item label="增值费用" prop="feeItemName">
              <el-input v-model="form.feeItemName" disabled />
            </el-form-item>
          </el-col>
          <!--          <el-col :span="24">-->
          <!--            <el-form-item label="备注" prop="remark">-->
          <!--              <el-input v-model="form.remark" disabled />-->
          <!--            </el-form-item>-->
          <!--          </el-col>-->
          <el-col :span="12">
            <el-form-item label="调账金额" prop="adjustAmount">
              <el-input v-model="form.adjustAmount" placeholder="请输入调账金额" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="调账类型" prop="adjustmentType">
              <el-select v-model="form.adjustmentType" placeholder="请选择">
                <el-option
                    v-for="item in adjustment_type"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="调账原因" prop="adjustmentReason">
              <el-input v-model="form.adjustmentReason" placeholder="请输入调账原因" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="CostList">
import { ref } from 'vue'
import { costDetailsList,getAccountAdjustment,putAccountAdjustment } from "@/api/logistics/monthSummary"

const { proxy } = getCurrentInstance()

const route = useRoute()
const routeQuery = route.query;

const { jd_logistics_product_code } = proxy.useDict("jd_logistics_product_code")
const { sf_logistics_product_code } = proxy.useDict("sf_logistics_product_code")
const { adjustment_type } = proxy.useDict("adjustment_type")

const loadingCost = ref(false);
const monthSummaryListCost = ref([]);
const totalCost = ref(0);
const queryParamsCost = ref({
  pageNum: 1,
  pageSize: 10,
})
const open = ref(false);
const form = ref({});
const rules = {
  adjustAmount: [
    {
      required: true, message: '请输入应付金额', trigger: 'blur'
    },
    {
      pattern: /^\d+(\.\d{1,2})?$/,
      message: "应付金额必须为数字，且最多保留两位小数",
      trigger: "blur"
    }
  ],
  adjustmentType: [
    {
      required: true, message: '请选择调账类型', trigger: 'change'
    },
  ]
}
const costListRef = ref(null)
function formatterOptions(options,value){
  const option = options.find(item => item.value === value)
  return option ? option.label : value
}

function getCostDetailsList(row){
  loadingCost.value = true
  queryParamsCost.value = {...routeQuery,...queryParamsCost.value}

  costDetailsList(queryParamsCost.value).then(response => {
    monthSummaryListCost.value = response.rows
    totalCost.value = response.total
    loadingCost.value = false
  })
}
function handleQueryCost(){
  queryParamsCost.value.pageNum = 1
  getCostDetailsList()
}
function resetQueryCost() {
  proxy.resetForm("queryCostRef")
  handleQueryCost()
}
function getAccountAdjustmentFn(row){
  let obj = {
    summaryMonth:row.summaryMonth,
    deptId:row.deptId,
    waybillDetailId:row.waybillDetailId
  }
  getAccountAdjustment(obj).then(response => {
    form.value = response.data;
    if(row.orderType == 1){
      form.value.goodsType = formatterOptions(jd_logistics_product_code.value,row.productCode)
    }else if(row.orderType == 2){
      form.value.goodsType = formatterOptions(sf_logistics_product_code.value,row.productCode)
    }
    form.value.payType = '月结';
    open.value = true;
  })
}
function handleUpdate(row){
  getAccountAdjustmentFn(row)
}
// 取消按钮
function cancel() {
  open.value = false
  form.value = {};
  proxy.resetForm("costListRef")
  if (costListRef.value) {
    costListRef.value.resetFields();
  }
}
async function submitForm () {
  if (!costListRef.value) {
    console.error('Form reference is not available');
    return;
  }

  try {
    // 使用 validate 方法进行表单验证
    const valid = await costListRef.value.validate();

    if (valid) {
      // 表单验证通过，提交数据
      console.log('表单验证通过，准备提交数据:', form.value);
      putAccountAdjustment(form.value).then(response => {
        proxy.$modal.msgSuccess("调账成功");
        open.value = false;

        // 重新加载数据
        getCostDetailsList();
      })
    }
  } catch (error) {
    console.error('表单验证失败:', error);
    // 验证失败，ElForm 会自动显示错误信息
  }
}
getCostDetailsList()
</script>
<style scoped>
.fontBlue{
  color: #2D71FF;
}
</style>