<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="100px">
      <el-form-item label="汇总月份" prop="summaryMonthRange">
        <el-date-picker
            v-model="summaryMonthRange"
            type="monthrange"
            range-separator="-"
            format="YYYY.MM"
            value-format="YYYY.MM"
            start-placeholder="开始月份"
            end-placeholder="结束月份"
            clearable
          @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" prop="deptName" />
      <el-table-column label="汇总月份" align="center" >
        <template #default="scope">
          <el-button
              type="text"
              @click="detailClick(scope.row)"
              v-if="auth.hasPermi('system:costDetails:list')"
              v-hasPermi="['system:costDetails:list']"
          >{{scope.row.summaryMonth}}</el-button>
          <span v-else>{{scope.row.summaryMonth}}</span>
        </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" width="120px" >
        <template #default="scope">
          <dict-tag :options="monthly_report_status" :value="scope.row.status" />
        </template>
      </el-table-column>

<!--      <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="140">
        <template #default="scope">
          <el-button
              type="text"
              @click="detailClick(scope.row)"
              v-hasPermi="['system:costDetails:list']"
              v-if="scope.row.status == 1"
          >调账</el-button>
          <el-button
              type="text"
              @click="detailClick(scope.row)"
              v-hasPermi="['system:costDetails:list']"
              v-if="scope.row.status == 2"
          >查看</el-button>
          <el-button link type="primary" @click="handleDuizhang(scope.row)" :disabled="scope.row.status != 1">对账</el-button>
          <el-button link type="primary" @click="handleKaipiao(scope.row)" :disabled="scope.row.status != 2">开票</el-button>
          <el-button link type="primary" @click="handlePiaojuhuichuan(scope.row)" :disabled="scope.row.status != 3">票据回传</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="openDuizhang" width="40%" append-to-body>
      <div class="info">
        <div>
          <span class="label">已勾选运单：</span>
          <span class="label">共<span class="font-red">{{form.transactionCount}}</span>单</span>
        </div>
        <div>
          <span class="label">账单费用：</span>
          <span class="label">应付金额<span class="font-red">{{form.payableAmount}}</span>元</span>
        </div>
        <div>
          <span class="label">注意：对账一经完成，无法修改，请谨慎操作。</span>
        </div>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="danger" @click="submitFormDZ">确 认</el-button>
          <el-button @click="openDuizhang = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 开票 -->
    <el-dialog title="申请开票" v-model="openKaipiao" width="70%" append-to-body>
      <el-form ref="formKPRef" :model="formKP" :rules="rulesKP" label-width="160px">
        <el-row>
          <el-col :span="24">
            <el-form-item label="开票金额共：" prop="BigDecimal">
              <div class="font-red">{{formKP.BigDecimal}}</div>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="发票抬头" prop="invoiceName">
              <el-input v-model="formKP.invoiceName" placeholder="请填写发票抬头" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="纳税人识别号" prop="invoiceNum">
              <el-input v-model="formKP.invoiceNum" placeholder="请填写购买方纳税人识别号" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="收票人邮箱" prop="email">
              <el-input v-model="formKP.email" placeholder="请填写收票人邮箱" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="地址" prop="companyAddress">
              <el-input v-model="formKP.companyAddress" placeholder="请填写准确的地址" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="电话" prop="phone">
              <el-input v-model="formKP.phone" placeholder="请填写7位或以上的电话号码" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="开户银行" prop="openBank">
              <el-input v-model="formKP.openBank" placeholder="请填写购买方开户行" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="银行账号" prop="bankAccount">
              <el-input v-model="formKP.bankAccount" placeholder="请填写购买方银行账号" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="备注说明" prop="remark">
              <el-input v-model="formKP.remark" placeholder="请填写需要在发票备注栏中显示的内容" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitFormKP">确 定</el-button>
          <el-button @click="openKaipiao = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="MonthSummary">
import { listMonthSummary, getMonthSummary, delMonthSummary, addMonthSummary, updateMonthSummary,invoiceIssuance,invoiceReturnShop } from "@/api/logistics/monthSummary"
import { getDept } from "@/api/system/dept"

import auth from '@/plugins/auth'
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 router = useRouter()

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 { queryParams, form, rules } = toRefs(data)
const openDuizhang = ref(false);
const summaryMonthRange = ref([]);
const openKaipiao = ref(false);
const formKP = reactive({
  invoiceName: '',
  invoiceNum: '',
  email: '',
  companyAddress: '',
  phone: '',
  openBank: '',
  bankAccount: '',
  remark: '',
  BigDecimal: 0,
  summaryId:undefined
});
const rulesKP = {
  invoiceName: [
    { required: true, message: '请填写发票抬头', trigger: 'blur' },
  ],
}
const formKPRef = ref(null)

/** 查询财务月度汇总列表 */
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;
  if(summaryMonthRange.value!=null && summaryMonthRange.value.length > 0){
    queryParams.value.summaryMonth = summaryMonthRange.value[0];
    queryParams.value.summaryMonthEnd = summaryMonthRange.value[1];
  }else{
    queryParams.value.summaryMonth = null;
    queryParams.value.summaryMonthEnd = null;
  }
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  summaryMonthRange.value =[];
  proxy.resetForm("queryRef")
  setDefaultMonthRange();
  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 handleDuizhang(row){
  form.value = row;
  openDuizhang.value = true;
}
// 对账确认
function submitFormDZ(){
  let obj = {
    summaryId:form.value.summaryId,
    status:2
  }
  updateMonthSummary(obj).then(response => {
    proxy.$modal.msgSuccess("修改成功")
    openDuizhang.value = false
    getList()
  })
}


// 点击开票
function handlePiaojuhuichuan(row){
  const params = {
    summaryId:row.summaryId
  }
  invoiceReturnShop(params).then(response => {
    if(response.code == 200){
      proxy.$modal.msgError(response.msg);
    }
    // proxy.$nextTick(() => {
      // Object.assign(formKP, {
      //   invoiceName: response.data.invoiceName || '',
      //   invoiceNum: response.data.invoiceNum || '',
      //   email: response.data.email || '',
      //   companyAddress: response.data.companyAddress || '',
      //   phone: response.data.phone || '',
      //   openBank: response.data.openBank || '',
      //   bankAccount: response.data.bankAccount || '',
      //   remark: response.data.remark || '',
      //   BigDecimal: row.payableAmount || 0,
      //   summaryId: row.summaryId || 0
      // });
      // openKaipiao.value = true;
    // });
  }).catch(error => {
    console.error('获取部门信息失败:', error);
    proxy.$modal.msgError('获取开票信息失败');
  });
}


// 点击开票
function handleKaipiao(row){
  getDept(row.deptId).then(response => {
    proxy.$nextTick(() => {
      Object.assign(formKP, {
        invoiceName: response.data.invoiceName || '',
        invoiceNum: response.data.invoiceNum || '',
        email: response.data.email || '',
        companyAddress: response.data.companyAddress || '',
        phone: response.data.phone || '',
        openBank: response.data.openBank || '',
        bankAccount: response.data.bankAccount || '',
        remark: response.data.remark || '',
        BigDecimal: row.payableAmount || 0,
        summaryId: row.summaryId || 0
      });
      openKaipiao.value = true;
    });
  }).catch(error => {
    console.error('获取部门信息失败:', error);
    proxy.$modal.msgError('获取开票信息失败');
  });
}
function submitFormKP(){
  let obj = {
    khmc:formKP.invoiceName,
    khsh:formKP.invoiceNum,
    hsje:formKP.BigDecimal,
    khdzdh:`${formKP.companyAddress} ${formKP.phone}`,
    khyhzh:`${formKP.openBank} ${formKP.bankAccount}`,
    gmfMobile:`${formKP.phone}`,
    gmfEmail:`${formKP.email}`,
    bz:`${formKP.remark}`,
    summaryId:formKP.summaryId
  }
  invoiceIssuance(obj).then(response => {
    proxy.$modal.msgSuccess("开票申请成功");
    openKaipiao.value = false;
  })
}
/** 导出按钮操作 */
function handleExport() {
  proxy.download('system/monthSummary/export', {
    ...queryParams.value
  }, `monthSummary_${new Date().getTime()}.xlsx`)
}
// 点击月份查看
function detailClick(row){
  router.push({
    path:'/money/costList',
    query:{
      summaryMonth:row.summaryMonth,
      deptId:row.deptId,
      status:row.status
    }
  })
}
// 计算上个月的日期范围
const setDefaultMonthRange = () => {
  const today = new Date();
  const currentYear = today.getFullYear();
  const currentMonth = today.getMonth() + 1; // 月份从0开始，所以要+1

  // 计算上个月
  let lastMonth = currentMonth - 1;
  let lastYear = currentYear;

  if (lastMonth === 0) {
    lastMonth = 12;
    lastYear = currentYear - 1;
  }

  // 格式化为 YYYY.MM
  const startDate = `${lastYear}.${String(lastMonth).padStart(2, '0')}`;
  const endDate = startDate; // 开始和结束相同，表示只选一个月

  summaryMonthRange.value = [startDate, endDate];

  // 同时设置查询参数
  queryParams.value.summaryMonth = startDate;
  queryParams.value.summaryMonthEnd = endDate;
};
setDefaultMonthRange();
getList()
</script>
<style scoped>
.font-red{
  color: #E4161F;
}
.info .label{
  font-size: 14px;
  color: #666;
}
</style>