<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="100px">
      <el-form-item label="汇总月份" prop="summaryMonth">
        <el-date-picker
            v-model="queryParams.summaryMonth"
            type="month"
            placeholder="选择月"
            clearable
            format="YYYY.MM"
            value-format="YYYY.MM"
          @change="handleQuery">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="供应商名称" prop="deptName">
        <el-input
          v-model="queryParams.deptName"
          placeholder="请输入供应商名称"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="账单状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择">
          <el-option
              v-for="item in monthly_report_status"
              :key="item.value"
              :label="item.label"
              :value="item.value">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
<!--      <el-col :span="1.5">-->
<!--        <el-button-->
<!--          type="primary"-->
<!--          plain-->
<!--          icon="Plus"-->
<!--          @click="handleAdd"-->
<!--          v-hasPermi="['system:monthSummary:add']"-->
<!--        >新增</el-button>-->
<!--      </el-col>-->
<!--      <el-col :span="1.5">-->
<!--        <el-button-->
<!--          type="success"-->
<!--          plain-->
<!--          icon="Edit"-->
<!--          :disabled="single"-->
<!--          @click="handleUpdate"-->
<!--          v-hasPermi="['system:monthSummary:edit']"-->
<!--        >修改</el-button>-->
<!--      </el-col>-->
<!--      <el-col :span="1.5">-->
<!--        <el-button-->
<!--          type="danger"-->
<!--          plain-->
<!--          icon="Delete"-->
<!--          :disabled="multiple"-->
<!--          @click="handleDelete"-->
<!--          v-hasPermi="['system:monthSummary:remove']"-->
<!--        >删除</el-button>-->
<!--      </el-col>-->
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['system:monthSummary:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="monthSummaryList">
<!--      <el-table-column type="selection" width="55" align="center" />-->
      <el-table-column label="月度汇总id" align="center" prop="summaryId" width="90" />
      <el-table-column label="汇总月份" align="center" >
        <template #default="scope">
          <div class="fontBlue" @click="detailClick(scope.row)">{{scope.row.summaryMonth}}</div>
        </template>
      </el-table-column>
      <el-table-column label="应付金额" align="center" prop="payableAmount" />
      <el-table-column label="交易笔数" align="center" prop="transactionCount" />
      <el-table-column label="账单状态" align="center" prop="status" >
        <template #default="scope">
          <span>{{formatterOptions(monthly_report_status,scope.row.status)}}</span>
        </template>
      </el-table-column>
      <el-table-column label="供应商" align="center" prop="deptName" />
      <el-table-column label="用户id" align="center" prop="userId" />
      <el-table-column label="百旺开票单据编号" align="center" prop="bwDjbh" />
      <el-table-column label="电子发票pdf地址" align="center" prop="bwDzfpPdfUrl" />
      <el-table-column label="电子发票ofd地址" align="center" prop="bwDzfpOfdUrl" />
      <el-table-column label="电子发票xml地址" align="center" prop="bwDzfpXmlUrl" />
      <el-table-column label="备注" align="center" prop="remark" />
<!--      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" fixed="right" width="160">-->
<!--        <template #default="scope">-->
<!--          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['system:monthSummary:edit']">修改</el-button>-->
<!--          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['system:monthSummary:remove']">删除</el-button>-->
<!--        </template>-->
<!--      </el-table-column>-->
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改财务月度汇总对话框 -->
    <el-dialog :title="title" v-model="open" width="70%" append-to-body>
      <el-form ref="monthSummaryRef" :model="form" :rules="rules" :inline="true" label-width="160px">
        <el-form-item label="汇总月份" prop="summaryMonth">
          <el-date-picker
              v-model="form.summaryMonth"
              type="month"
              placeholder="选择月"
              clearable
              value-format="yyyy-MM">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="应付金额" prop="payableAmount">
          <el-input v-model="form.payableAmount" placeholder="请输入应付金额" />
        </el-form-item>
        <el-form-item label="交易笔数" prop="transactionCount">
          <el-input v-model="form.transactionCount" placeholder="请输入交易笔数" />
        </el-form-item>
        <el-form-item label="账单状态" prop="status">
          <el-select v-model="form.status" placeholder="请选择">
            <el-option
                v-for="item in monthly_report_status"
                :key="item.value"
                :label="item.label"
                :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="供应商名称" prop="deptId">
          <el-input v-model="form.deptId" placeholder="请输入部门ID" />
        </el-form-item>
        <el-form-item label="用户id" prop="userId">
          <el-input v-model="form.userId" placeholder="请输入用户id" />
        </el-form-item>
        <el-form-item label="百旺开票单据编号" prop="bwDjbh">
          <el-input v-model="form.bwDjbh" placeholder="请输入百旺开票单据编号" />
        </el-form-item>
        <el-form-item label="电子发票pdf地址" prop="bwDzfpPdfUrl">
          <el-input v-model="form.bwDzfpPdfUrl" placeholder="请输入电子发票pdf地址" />
        </el-form-item>
        <el-form-item label="电子发票ofd地址" prop="bwDzfpOfdUrl">
          <el-input v-model="form.bwDzfpOfdUrl" placeholder="请输入电子发票ofd地址" />
        </el-form-item>
        <el-form-item label="电子发票xml地址" prop="bwDzfpXmlUrl">
          <el-input v-model="form.bwDzfpXmlUrl" placeholder="请输入电子发票xml地址" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" placeholder="请输入备注" />
        </el-form-item>
      </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>

<!--    查看-->
    <el-dialog title="查看" v-model="openDetail" width="80%" append-to-body>
      <el-form :model="queryParamsCost" ref="queryCostRef" :inline="true" v-show="showSearch" 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" />
        <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>

      <pagination
          v-show="totalCost>0"
          :total="totalCost"
          v-model:page="queryParamsCost.pageNum"
          v-model:limit="queryParamsCost.pageSize"
          @pagination="getCostDetailsList"
      />
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="openDetail = false">返 回</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="MonthSummary">
import { listMonthSummary, getMonthSummary, delMonthSummary, addMonthSummary, updateMonthSummary,costDetailsList } from "@/api/logistics/monthSummary"

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

const monthSummaryList = ref([])
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref("")

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    summaryMonth: null,
    payableAmount: null,
    transactionCount: null,
    status: null,
    deptId: null,
    userId: null,
    bwDjbh: null,
    bwDzfpPdfUrl: null,
    bwDzfpOfdUrl: null,
    bwDzfpXmlUrl: null,
  },
  monthly_report_status:[],
  rules: {
    payableAmount: [
      {
        pattern: /^\d+(\.\d{1,2})?$/,
        message: "应付金额必须为数字，且最多保留两位小数",
        trigger: "blur"
      }
    ],
    transactionCount: [
      {
        pattern: /^[1-9]\d*$/,
        message: "交易笔数必须为正整数",
        trigger: "blur"
      }
    ]
  }
})
const openDetail = ref(false);
const loadingCost = ref(false);
const monthSummaryListCost = ref([]);
const totalCost = ref(0);
const queryParamsCost = ref({
  pageNum: 1,
  pageSize: 10,
})

const { queryParams, form, rules } = toRefs(data)

/** 查询财务月度汇总列表 */
function getList() {
  loading.value = true
  listMonthSummary(queryParams.value).then(response => {
    monthSummaryList.value = response.rows
    total.value = response.total
    loading.value = false
  })
}

// 取消按钮
function cancel() {
  open.value = false
  reset()
}

// 表单重置
function reset() {
  form.value = {
    summaryId: null,
    summaryMonth: null,
    payableAmount: null,
    transactionCount: null,
    status: null,
    createTime: null,
    updateTime: null,
    remark: null,
    delFlag: null,
    createBy: null,
    updateBy: null,
    deptId: null,
    userId: null,
    bwDjbh: null,
    bwDzfpPdfUrl: null,
    bwDzfpOfdUrl: null,
    bwDzfpXmlUrl: null
  }
  proxy.resetForm("monthSummaryRef")
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef")
  handleQuery()
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.summaryId)
  single.value = selection.length != 1
  multiple.value = !selection.length
}

/** 新增按钮操作 */
function handleAdd() {
  reset()
  open.value = true
  title.value = "添加财务月度汇总"
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset()
  const _summaryId = row.summaryId || ids.value
  getMonthSummary(_summaryId).then(response => {
    form.value = response.data
    open.value = true
    title.value = "修改财务月度汇总"
  })
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["monthSummaryRef"].validate(valid => {
    if (valid) {
      if (form.value.summaryId != null) {
        updateMonthSummary(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功")
          open.value = false
          getList()
        })
      } else {
        addMonthSummary(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功")
          open.value = false
          getList()
        })
      }
    }
  })
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _summaryIds = row.summaryId || ids.value
  proxy.$modal.confirm('是否确认删除财务月度汇总编号为"' + _summaryIds + '"的数据项？').then(function() {
    return delMonthSummary(_summaryIds)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => {})
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('system/monthSummary/export', {
    ...queryParams.value
  }, `monthSummary_${new Date().getTime()}.xlsx`)
}
function formatterOptions(options,value){
  console.log(options,value)
  const option = options.find(item => item.value === value)
  return option ? option.label : value
}
// 点击月份查看
function detailClick(row){
  openDetail.value = true;
  queryParamsCost.value.summaryMonth = row.summaryMonth;
  queryParamsCost.value.deptId = row.deptId;
  getCostDetailsList();
}
function getCostDetailsList(row){
  loadingCost.value = true

  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()
}
getList()
</script>
<style scoped>
.fontBlue{
  color: #2D71FF;
}
</style>