<template>
  <div class="app-container">
    <el-card>
      <el-form ref="formSearch" :model="formQuery" label-width="100px" label-position="left" :inline="true">
        <el-form-item :label="$t('编号') + ':'" style="margin-bottom: 0; margin-top: 20px" label-width="100px" prop="orderNumber">
          <el-input v-model="formQuery.orderNumber" style="width: 260px" :placeholder="$t('订单号/提单号')">
            <template slot="prepend"> <dict-selector :type="DICT_TYPE.ORDER_QUERY_NO_FIELD" defaultable v-model="formQuery.key" /> </template
          ></el-input>
        </el-form-item>
        <el-form-item :label="$t('付款方') + ':'" style="margin-bottom: 0; margin-top: 20px" label-width="100px" prop="payerType">
          <el-select style="width: 260px" v-model="formQuery.payerType" clearable>
            <el-option :label="$t('发货方')" value="1"></el-option>
            <el-option :label="$t('收货方')" value="2"></el-option>
            <el-option :label="$t('自定义')" value="3"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item :label="$t('收款日期') + ':'" style="margin-bottom: 0; margin-top: 20px" label-width="100px" prop="timeData">
          <el-date-picker v-model="formQuery.timeData" type="datetimerange" value-format="yyyy-MM-dd HH:mm:ss" format="yyyy-MM-dd HH:mm:ss" range-separator="-" :start-placeholder="$t('开始日期')" :end-placeholder="$t('结束日期')"></el-date-picker>
        </el-form-item>
        <el-form-item :label="$t('收款账号') + ':'" style="margin-bottom: 0; margin-top: 20px" label-width="100px" prop="accountId">
          <el-select style="width: 260px" multiple clear v-model="formQuery.accountId" :placeholder="$t('请选择收款账户')">
            <el-option v-for="(item, i) in bankData" :key="'opt-code' + i" :label="item.baAccountName + '(' + item.baAccountNum + ')'" :value="item.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item :label="$t('客户经理') + ':'" style="margin-bottom: 0; margin-top: 20px" label-width="100px" prop="salesmanIds">
          <user-selector style="width: 260px" multiple manage v-model="formQuery.salesmanIds" clearable :placeholder="$t('请选择')" />
        </el-form-item>
        <el-form-item :label="$t('客户') + ':'" style="margin-bottom: 0; margin-top: 20px" label-width="100px" prop="customerName">
          <el-input style="width: 260px" v-model="formQuery.customerName" :placeholder="$t('请输入客户')"> ></el-input>
        </el-form-item>
        <el-form-item :label="$t('提交时间') + ':'" style="margin-bottom: 0; margin-top: 20px" label-width="100px" prop="endTimeData">
          <el-date-picker v-model="formQuery.endTimeData" type="datetimerange" value-format="yyyy-MM-dd HH:mm:ss" format="yyyy-MM-dd HH:mm:ss" range-separator="-" :start-placeholder="$t('开始日期')" :end-placeholder="$t('结束日期')"></el-date-picker>
        </el-form-item>
        <el-form-item style="padding-left: 20px; margin-bottom: 0; margin-top: 20px">
          <el-button type="primary" icon="el-icon-search" @click="getList">{{ $t("搜索") }}</el-button>
          <el-button icon="el-icon-refresh" @click="resetQuery">{{ $t("重置") }}</el-button>
        </el-form-item>
      </el-form>
    </el-card>
    <el-row :gutter="10" class="mb8 pad-t">
      <el-col :span="1.5">
        <el-button @click="batchApprove('approval')" type="primary" plain icon="el-icon-plus" size="mini">{{ $t("批量通过") }} </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="primary" @click="batchApprove('unApproval')" size="mini">{{ $t("批量不通过") }}</el-button>
      </el-col>
    </el-row>
    <el-card>
      <el-descriptions class="margin-top barTop" :column="2" border>
        <el-descriptions-item>
          <template slot="label"> {{ $t("实收金额汇总") }}: </template>
          <span class="unit" v-for="item in actualAmountList" :key="item.currencyId">{{ getCurrencySymbol(item.currencyId * 1) }}{{ item.amount }}</span>
        </el-descriptions-item>
      </el-descriptions>
    </el-card>
    <div class="tableTop">
      <el-table v-loading="loading" :data="receiptApproveList" @selection-change="handleSelectionChange" border>
        <el-table-column type="selection" width="55"> </el-table-column>
        <el-table-column :label="$t('订单号')" width="160" fixed="left" align="center">
          <template slot-scope="{ row }">
            <div v-for="item in row.orderInfoList" :key="item.orderId">
              <router-link :to="`/order/detail?orderId=${item.orderId}`" class="link-type"> {{ item.orderNo }}/{{ item.tidanNo }} </router-link>
              <dict-tag :type="DICT_TYPE.ORDER_STATUS" :value="item.status" />
            </div>
            <!-- <span style="color: #1890ff" @click="paymentDetail2(scope.row)">{{ scope.row.orderNo }}</span> -->
          </template>
        </el-table-column>
        <el-table-column :label="$t('收款单号')" fixed="left" width="160" align="center" prop="receiptNo"> </el-table-column>
        <el-table-column :label="$t('付款方')" width="160" align="center">
          <template slot-scope="scope">
            <span v-if="scope.row.payerType == 3"> {{ $t("自定义") }}</span>
            <span v-else> {{ scope.row.payerType == 1 ? $t("发货人") : $t("收货人") }}</span>
          </template>
        </el-table-column>
        <el-table-column :label="$t('费用')" width="160" align="center">
          <template slot-scope="{ row }">
            <div>
              {{ $t("明细") }}:
              <span class="feeStatistics" v-for="item in row.feeStatistics.details"> <dict-tag :type="DICT_TYPE.FEE_TYPE" :value="item.feeType" />:{{ item.feeAmount }}</span>
            </div>
            <div>
              {{ $t("汇总") }}:
              {{ row.feeStatistics.summary }}
            </div>
            <div>
              {{ $t("结算币种") }}:
              {{ row.feeStatistics.baseCurrencySummary }}
            </div>
          </template>
        </el-table-column>
        <el-table-column :label="$t('收款日期')" width="160" align="center" prop="amountDate"> </el-table-column>
        <el-table-column :label="$t('收款账号')" width="160" align="center" prop="accountName"> </el-table-column>
        <el-table-column :label="$t('实收金额')" width="160" align="center" prop="amount" :formatter="formatCurrency"> </el-table-column>
        <el-table-column :label="$t('汇率')" width="160" align="center" prop="rate"> </el-table-column>
        <el-table-column :label="$t('结算币种金额')" :formatter="formatCurrency" width="160" align="center" prop="writeOffAmount"> </el-table-column>
        <el-table-column :label="$t('附件')" width="160" align="center">
          <template slot-scope="scope">
            <div v-if="scope.row.attr">
              <div v-for="url in scope.row.attr.split(',').filter((item) => !!item)">
                <el-link :href="url" target="_blank">{{ url.split("/").pop() }}</el-link>
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column :label="$t('备注')" width="160" align="center" prop="remark"> </el-table-column>
        <el-table-column :label="$t('客户')" width="160" align="center">
          <template v-slot="{ row }">
            <router-link :to="`/customer/query/${row.customerId}`" class="link-type">
              {{ row.customerName }}
            </router-link>
          </template>
        </el-table-column>
        <el-table-column :label="$t('客户经理')" width="160" align="center" prop="salesmanName"> </el-table-column>
        <el-table-column :label="$t('提交时间')" width="160" align="center" prop="submitTime"> </el-table-column>
        <el-table-column :label="$t('操作')" width="160" fixed="right" align="center">
          <template v-slot="{ row }">
            <el-button size="mini" type="text" icon="el-icon-edit" @click="handleAudit(row)" v-hasPermi="['ecw:collectionApprovalList:update']">{{ $t("审批") }} </el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-card>
        <el-descriptions class="margin-top barTop" :column="2" border>
          <el-descriptions-item>
            <template slot="label"> {{ $t("实收金额合计") }}: </template>
            <span class="unit" v-for="item in totalActualAmountList" :key="item.currencyId">{{ getCurrencySymbol(item.currencyId * 1) }}{{ item.amount }}</span>
          </el-descriptions-item>
          <el-descriptions-item>
            <template slot="label"> {{ $t("结算币种金额合计") }}: </template>
            <span class="unit" v-for="item in totalWriteOffAmountList" :key="item.currencyId">{{ getCurrencySymbol(item.currencyId * 1) }}{{ item.amount }}</span>
          </el-descriptions-item>
        </el-descriptions>
      </el-card>
      <pagination v-show="total > 0" :total="total" :page.sync="formQuery.page" :limit.sync="formQuery.rows" @pagination="handleQuery" />
    </div>

    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="审批意见" prop="comment">
          <el-input v-model="form.comment" style="width: 300px" placeholder="请输入审批意见" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import UserSelector from "@/components/UserSelector/index.vue"
import { getBankAccountPage } from "@/api/ecw/bankAccount"
import { loadReceiptReviewList } from "@/api/ecw/financial"
import { mapGetters } from "vuex"
import { approveTask2, rejectTask2 } from "@/api/bpm/task"
export default {
  components: {
    UserSelector
  },
  data() {
    return {
      total: 0,
      bankData: [],
      loading: false,
      actualAmountList: [],
      totalActualAmountList: [],
      totalWriteOffAmountList: [],
      open: false,
      title: "",
      receiptApproveList: [],
      form: {
        //审批意见
        comment: undefined
      },
      ids: [],
      rules: {
        comment: [
          {
            required: true,
            message: this.$t("审批意见不能为空。"),
            trigger: "blur"
          }
        ]
      },
      formQuery: {
        key: "",
        orderNumber: "",
        payerType: "",
        timeData: [],
        endTimeData: [],
        accountId: [],
        salesmanIds: [],
        customerName: "",
        page: 1,
        rows: 10
      }
    }
  },
  created() {
    this.getBankDataList()
    this.handleQuery()
  },
  computed: {
    ...mapGetters(["getCurrencySymbol"])
  },
  methods: {
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (!valid) {
          return
        }
        //approveTask2
        if (this.titleType == 1) {
          let p1 = []
          for (var i = 0; i < this.ids.length; i++) {
            var obj = {}
            obj.id = this.ids[i].bmpId
            obj.comment = this.form.comment
            p1.push(obj)
          }
          approveTask2(p1).then((response) => {
            if (response.data == true) {
              this.open = false
              this.$modal.msgSuccess(this.$t("批量处理成功"))
              this.handleQuery()
            } else {
              this.open = false
              this.$modal.msgSuccess(this.$t("批量处理失败"))
            }
          })
        } else {
          let p2 = []
          for (var i = 0; i < this.ids.length; i++) {
            var obj = {}
            obj.id = this.ids[i].bmpId
            obj.comment = this.form.comment
            p2.push(obj)
          }
          rejectTask2(p2).then((response) => {
            if (response.data == true) {
              this.open = false
              this.$modal.msgSuccess(this.$t("批量处理成功"))
              this.handleQuery()
            } else {
              this.open = false
              this.$modal.msgSuccess(this.$t("批量处理失败"))
            }
          })
        }
      })
    },
    cancel() {
      this.title = ""
      this.open = false
    },
    // 批量审批
    batchApprove(key) {
      if (this.ids.length == 0) {
        //this.modal.msgSuccess
        this.$message.error(this.$t("请选择需要批量操作的任务。"))
        return
      }
      this.form.comment = ""
      if (key == "approval") {
        this.title = this.$t("批量通过")
        this.titleType = 1
      } else {
        this.title = this.$t("批量不通过")
        this.titleType = 2
      }

      this.open = true
    },
    /** 处理审批按钮 */
    handleAudit(row) {
      this.$router.push({
        path: "/bpm/process-instance/detail2",
        query: { id: row.bmpId }
      })
    },
    // 用于格式化货币的函数
    formatCurrency(row, column, cellValue) {
      if (column.property == "writeOffAmount") {
        return this.getCurrencySymbol(row.writeOffCurrencyId) + (cellValue || "0")
      }
      return this.getCurrencySymbol(row.currencyId) + (cellValue || "0")
    },
    handleSelectionChange(val) {
      this.ids = val
    },
    getList() {
      this.formQuery.page = 1
      this.handleQuery()
    },
    async handleQuery() {
      this.loading = true
      let params = { ...this.formQuery }
      this.addBeginAndEndTime(params, this.formQuery.timeData, "CreateTime")
      this.addBeginAndEndTime(params, this.formQuery.endTimeData, "AmountDate")
      if (params.key && params.orderNumber) {
        params[params.key] = params.orderNumber
      }
      const { data } = await loadReceiptReviewList(params)
      this.actualAmountList = data.actualAmount
      this.totalActualAmountList = data.totalActualAmount
      this.totalWriteOffAmountList = data.totalWriteOffAmount
      this.loading = false
      this.receiptApproveList = data.list
      this.total = data.total
      console.log("99999", data)
    },
    resetQuery() {
      this.formQuery = {
        key: "",
        orderNumber: "",
        payerType: "",
        timeData: [],
        endTimeData: "",
        accountId: [],
        salesmanIds: [],
        customerName: "",
        page: 1,
        rows: 10
      }
    },
    getBankDataList() {
      getBankAccountPage({ pageNo: 1, pageSize: 1000 }).then((res) => {
        this.bankData = res.data.list
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.feeStatistics {
  padding: 0 6px;
}
.pad-t {
  padding: 10px 0;
}
.unit {
  padding-left: 10px;
}
</style>
