<template>
  <div class="app-container">
    <div class="title">
      {{ $t("批量生成收款单") }}
    </div>
    <div class="btn-box">
      <el-button type="primary" size="small" @click="setReceiptInfo">{{ $t("设置收款单信息") }}</el-button>
      <el-button type="primary" size="small" @click="setWhetherToInvoice">{{ $t("设置是否开票") }}</el-button>
      <el-button type="primary" size="small" @click="setInvoiceInfo">{{ $t("设置开票信息") }}</el-button>
    </div>
    <div class="table-box">
      <el-table ref="multipleTable" :row-class-name="tableRowClassName" v-loading="loading" :data="list" @selection-change="handleSelectionChange" border>
        <el-table-column type="selection" width="55" align="center" fixed="left" />
        <el-table-column width="200" align="center" :label="$t('运输信息')">
          <template v-slot="{ row }"> {{ getWareHouseLabel(row.departureWareHouseId) }}- <dict-tag :type="DICT_TYPE.ECW_TRANSPORT_TYPE" :value="row.transportId"></dict-tag> /{{ getWareHouseLabel(row.objectiveWareHouseId) }} </template>
        </el-table-column>
        <el-table-column :label="$t('订单号')" prop="orderNo">
          <template slot-scope="scope">
            <router-link
              :to="{
                path: '/order/detail',
                query: { orderId: scope.row.orderId }
              }"
              class="link-type"
            >
              <span>{{ scope.row.orderNo }}</span>
            </router-link>
          </template>
        </el-table-column>
        <el-table-column :label="$t('提单号')" prop="tidanNo" />
        <el-table-column :label="$t('付款方')" width="160" align="center">
          <template slot-scope="scope">
            <span v-if="scope.row.drawee == 3"> {{ $t("自定义") }}</span>
            <span v-else> {{ scope.row.drawee == 1 ? $t("发货人") : $t("收货人") }}</span>
          </template>
        </el-table-column>
        <el-table-column :label="$t('付款名称')" width="160" align="center">
          <template v-slot="{ row }">
            <div>
              <router-link :to="`/customer/query/${row.payerId}`" class="link-type">
                {{ row.customerNo }}
              </router-link>
            </div>
            <div>{{ row.payerName ? row.payerName : row.customerName }}</div>
          </template>
        </el-table-column>

        <el-table-column :label="$t('费用明细')">
          <template v-slot="{ row }">
            <div>
              <router-link :to="`/financial/orderItemCostDetails/${row.orderId}/${row.drawee}`" class="link-type">
                {{ $t("费用明细") }}
              </router-link>
            </div>
          </template>
        </el-table-column>
        <el-table-column :label="$t('收款明细税率%')" prop="taxPoint"> </el-table-column>
        <el-table-column :label="$t('期望收款账号')" prop="platformAccountName"> </el-table-column>
        <el-table-column :label="$t('汇率有效期')" width="200" prop="rateValidateDate"> </el-table-column>
        <el-table-column :label="$t('备注')" width="200" prop="remark"> </el-table-column>
        <el-table-column :label="$t('是否开票')">
          <template v-slot="{ row }">
            <span v-if="row.openInvoice == '1'">
              {{ $t("是") }}
            </span>
            <span v-else-if="row.openInvoice == '0'">
              {{ $t("否") }}
            </span>
            <span v-else> - </span>
          </template>
        </el-table-column>
        <el-table-column :label="$t('开票抬头')" prop="invoice"> </el-table-column>
        <el-table-column :label="$t('纳税人识别号')" prop="taxpayer"> </el-table-column>
        <el-table-column :label="$t('开户行')" prop="accountBank"> </el-table-column>
        <el-table-column :label="$t('账号')" prop="accountName"> </el-table-column>
        <el-table-column :label="$t('开票品名')" prop="projectName"> </el-table-column>
        <el-table-column :label="$t('开票税率')" prop="taxRate"> </el-table-column>

        <el-table-column :label="$t('开票地址/电话')" prop="addressPhone"> </el-table-column>
        <el-table-column :label="$t('操作')" fixed="right">
          <template v-slot="{ row }">
            <el-button type="primary" @click="openSingleEditDialog(row)" size="small">{{ $t("编辑") }}</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="footer">
      <el-button type="primary" @click="submitList">{{ $t("提交") }}</el-button>
    </div>

    <!-- 单个 编辑 弹窗-->
    <el-dialog :before-close="handleCloseBefore" :title="$t('编辑')" :visible.sync="openSinglEditForm" width="500" append-to-body>
      <div class="pad-t">{{ $t("已选择订单/提单") }}:{{ singlEditForm.orderNo }}-{{ singlEditForm.tidanNo }}</div>
      <el-form ref="singlEditForm" :model="singlEditForm" label-width="160px">
        <div class="title">{{ $t("收款信息") }}</div>

        <el-form-item :label="$t('收款明细税率')" prop="taxPoint">
          <el-input v-model="singlEditForm.taxPoint" style="width: 200px" :placeholder="$t('请输入收款明细税率')" />
        </el-form-item>
        <el-form-item :label="$t('期望收款账号')" prop="platformAccountId">
          <el-select style="width: 200px" filterable clear v-model="singlEditForm.platformAccountId" :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('汇率有效期')" prop="rateValidateDate">
          <el-date-picker style="width: 200px" v-model="singlEditForm.rateValidateDate" type="datetime" value-format="yyyy-MM-dd HH:mm:ss" :placeholder="$t('选择日期时间')"> </el-date-picker>
        </el-form-item>
        <el-form-item :label="$t('备注')">
          <el-input style="width: 200px" v-model="singlEditForm.remark" maxlength="500"></el-input>
        </el-form-item>
        <div class="title">{{ $t("开票信息") }}</div>
        <el-form-item
          :label="$t('是否开票')"
          prop="openInvoice"
          :rules="{
            required: true,
            trigger: ['blur', 'change'],
            message: $t('请选择是否开票')
          }"
        >
          <el-select style="width: 200px" v-model="singlEditForm.openInvoice" :placeholder="$t('请选择是否需要开票')">
            <el-option :value="1" :label="$t('是')"></el-option>
            <el-option :value="0" :label="$t('否')"></el-option>
          </el-select>
        </el-form-item>
        <div v-if="singlEditForm.openInvoice == 1">
          <el-form-item
            :label="$t('发票抬头')"
            prop="invoice"
            :rules="{
              required: true,
              trigger: ['blur', 'change'],
              message: $t('请输入发票抬头')
            }"
          >
            <el-input style="width: 200px" v-model="singlEditForm.invoice"></el-input>
          </el-form-item>
          <el-form-item
            :label="$t('纳税人识别号')"
            prop="taxpayer"
            :rules="{
              required: true,
              trigger: ['blur', 'change'],
              message: $t('请输入纳税人识别号')
            }"
          >
            <el-input style="width: 200px" v-model="singlEditForm.taxpayer"></el-input>
          </el-form-item>
          <el-form-item
            :label="$t('开户行')"
            prop="accountBank"
            :rules="{
              required: true,
              trigger: ['blur', 'change'],
              message: $t('请输入开户行')
            }"
          >
            <el-input style="width: 200px" v-model="singlEditForm.accountBank"></el-input>
          </el-form-item>
          <el-form-item
            :label="$t('账号')"
            prop="accountName"
            :rules="{
              required: true,
              trigger: ['blur', 'change'],
              message: $t('请输入账号')
            }"
          >
            <el-input style="width: 200px" v-model="singlEditForm.accountName"></el-input>
          </el-form-item>
          <el-form-item
            :label="$t('开票品名')"
            prop="projectName"
            :rules="{
              required: true,
              trigger: ['blur', 'change'],
              message: $t('请输入开票品名')
            }"
          >
            <el-input style="width: 200px" v-model="singlEditForm.projectName"></el-input>
          </el-form-item>
          <el-form-item
            :label="$t('开票税率')"
            prop="taxRate"
            :rules="{
              required: true,
              trigger: ['blur', 'change'],
              message: $t('请输入税率')
            }"
          >
            <el-input-number style="width: 200px" :controls="false" v-model="singlEditForm.taxRate"></el-input-number>
          </el-form-item>
          <el-form-item
            :label="$t('开票地址/电话')"
            prop="addressPhone"
            :rules="{
              required: true,
              trigger: ['blur', 'change'],
              message: $t('请输入开票地址/电话')
            }"
          >
            <el-input style="width: 200px" v-model="singlEditForm.addressPhone"></el-input>
          </el-form-item>
        </div>
        <!-- <el-form-item :label="$t('开票资料备注')">
          <el-input style="width: 280px" v-model="singlEditForm.invoiceRemark"></el-input>
        </el-form-item> -->
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitSingleForm">{{ $t("确 定") }}</el-button>
        <el-button @click="cancel">{{ $t("取 消") }}</el-button>
      </div>
    </el-dialog>

    <!-- 批量设置收款单信息 -->
    <el-dialog :before-close="handleCloseBefore" :title="$t('批量设置收款单信息')" :visible.sync="openBatchReceiptInfo" width="500" append-to-body>
      <div class="pat-t orderBox">
        <div class="left">{{ $t("已选择订单/提单") }}</div>
        <div class="right">
          <div class="orderInfoItem" v-for="item in multipleSelectedList">{{ item.orderNo }}/{{ item.tidanNo }}</div>
        </div>
      </div>
      <el-form ref="singlEditForm" :model="singlEditForm" label-width="160px">
        <el-form-item :label="$t('收款明细税率')" prop="taxPoint">
          <el-input v-model="singlEditForm.taxPoint" style="width: 200px" :placeholder="$t('请输入收款明细税率')" />
        </el-form-item>
        <el-form-item :label="$t('期望收款账号')" prop="platformAccountId">
          <el-select style="width: 200px" filterable clear v-model="singlEditForm.platformAccountId" :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('汇率有效期')" prop="rateValidateDate">
          <el-date-picker style="width: 200px" v-model="singlEditForm.rateValidateDate" type="datetime" value-format="yyyy-MM-dd HH:mm:ss" :placeholder="$t('选择日期时间')"> </el-date-picker>
        </el-form-item>
        <el-form-item :label="$t('备注')">
          <el-input style="width: 200px" v-model="singlEditForm.remark" maxlength="500"></el-input>
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitBatchReceipt">{{ $t("确 定") }}</el-button>
        <el-button @click="cancel">{{ $t("取 消") }}</el-button>
      </div>
    </el-dialog>
    <!-- 批量设置是否开票 -->
    <el-dialog :before-close="handleCloseBefore" :title="$t('设置是否开票')" :visible.sync="openSetsWhetherToInvoice" width="500" append-to-body>
      <div class="pat-t orderBox">
        <div class="left">{{ $t("已选择订单/提单") }}</div>
        <div class="right">
          <div class="orderInfoItem" v-for="item in multipleSelectedList">{{ item.orderNo }}/{{ item.tidanNo }}</div>
        </div>
      </div>
      <el-form ref="singlEditForm" :model="singlEditForm" label-width="160px">
        <el-form-item
          :label="$t('是否开票')"
          prop="openInvoice"
          :rules="{
            required: true,
            trigger: ['blur', 'change'],
            message: $t('请选择是否开票')
          }"
        >
          <el-select style="width: 200px" v-model="singlEditForm.openInvoice" :placeholder="$t('请选择是否需要开票')">
            <el-option :value="1" :label="$t('是')"></el-option>
            <el-option :value="0" :label="$t('否')"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitBatchReceipt">{{ $t("确 定") }}</el-button>
        <el-button @click="cancel">{{ $t("取 消") }}</el-button>
      </div>
    </el-dialog>
    <!-- 批量设置开票信息 -->
    <el-dialog :before-close="handleCloseBefore" :title="$t('设置开票信息')" :visible.sync="openBatchInvoiceInfo" width="500" append-to-body>
      <el-form ref="singlEditForm" :model="singlEditForm" label-width="160px">
        <div>
          <el-form-item
            :label="$t('发票抬头')"
            prop="invoice"
            :rules="{
              required: true,
              trigger: ['blur', 'change'],
              message: $t('请输入发票抬头')
            }"
          >
            <el-input style="width: 200px" v-model="singlEditForm.invoice"></el-input>
          </el-form-item>
          <el-form-item
            :label="$t('纳税人识别号')"
            prop="taxpayer"
            :rules="{
              required: true,
              trigger: ['blur', 'change'],
              message: $t('请输入纳税人识别号')
            }"
          >
            <el-input style="width: 200px" v-model="singlEditForm.taxpayer"></el-input>
          </el-form-item>
          <el-form-item
            :label="$t('开户行')"
            prop="accountBank"
            :rules="{
              required: true,
              trigger: ['blur', 'change'],
              message: $t('请输入开户行')
            }"
          >
            <el-input style="width: 200px" v-model="singlEditForm.accountBank"></el-input>
          </el-form-item>
          <el-form-item
            :label="$t('账号')"
            prop="accountName"
            :rules="{
              required: true,
              trigger: ['blur', 'change'],
              message: $t('请输入账号')
            }"
          >
            <el-input style="width: 200px" v-model="singlEditForm.accountName"></el-input>
          </el-form-item>
          <el-form-item
            :label="$t('开票品名')"
            prop="projectName"
            :rules="{
              required: true,
              trigger: ['blur', 'change'],
              message: $t('请输入开票品名')
            }"
          >
            <el-input style="width: 200px" v-model="singlEditForm.projectName"></el-input>
          </el-form-item>
          <el-form-item
            :label="$t('开票税率')"
            prop="taxRate"
            :rules="{
              required: true,
              trigger: ['blur', 'change'],
              message: $t('请输入税率')
            }"
          >
            <el-input-number style="width: 200px" :controls="false" v-model="singlEditForm.taxRate"></el-input-number>
          </el-form-item>
          <el-form-item
            :label="$t('开票地址/电话')"
            prop="addressPhone"
            :rules="{
              required: true,
              trigger: ['blur', 'change'],
              message: $t('请输入开票地址/电话')
            }"
          >
            <el-input style="width: 200px" v-model="singlEditForm.addressPhone"></el-input>
          </el-form-item>
        </div>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitBatchReceipt">{{ $t("确 定") }}</el-button>
        <el-button @click="cancel">{{ $t("取 消") }}</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getWarehouseList } from "@/api/ecw/warehouse"
import { loadBatGNRTReceiptList, handleBankGNRTReceipt } from "@/api/ecw/financial"
import { getBankAccountPage } from "@/api/ecw/bankAccount"
import { deepClone } from "@/utils"
export default {
  name: "EcwFinancialBatchgeneratereceipt",
  data() {
    return {
      openBatchReceiptInfo: false, //   批量设置收款单信息
      openSetsWhetherToInvoice: false, // 批量设置是否开票
      openBatchInvoiceInfo: false, //批量设置信息
      bankData: [],
      singlEditForm: {},
      selectStatusList: [],
      openSinglEditForm: false,
      loading: false,
      multipleSelectedList: [],
      list: [],
      queryParams: {
        orderIds: [],
        page: 1,
        rows: 10
      }
    }
  },
  created() {
    getWarehouseList().then((res) => {
      this.loadOrderDataList()
      this.warehouseList = res.data
    })
    getBankAccountPage({ pageNo: 1, pageSize: 1000 }).then((res) => {
      this.bankData = res.data.list
    })
    this.queryParams.orderIds = this.$route.params.id.split(",")
  },
  methods: {
    setWhetherToInvoice() {
      if (this.multipleSelectedList.length == 0) {
        this.$modal.msgError(`请先选择需要批量处理的订单`)
        return
      }
      this.openSetsWhetherToInvoice = true
      this.$nextTick(() => {
        this.$refs["singlEditForm"].clearValidate()
      })
    },
    setInvoiceInfo() {
      if (this.multipleSelectedList.length == 0) {
        this.$modal.msgError(`请先选择需要批量处理的订单`)
        return
      }
      const stringLabel = []
      let multiple = this.multipleSelectedList.filter((item) => {
        if (item.openInvoice == 0) {
          stringLabel.push(item.tidanNo + "/" + item.orderNo)
        }
        return item.openInvoice == 0
      })
      if (multiple.length > 0) {
        this.$modal.msgError(`订单/提单号:${stringLabel}状态为不开票，无需设置开票信息`)
        return
      }
      this.openBatchInvoiceInfo = true //批量设置信息
      this.$nextTick(() => {
        this.$refs["singlEditForm"].clearValidate()
      })
    },
    //批量设置收款单信息
    async submitBatchReceipt() {
      const result = await this.validateFormResult("singlEditForm")
      if (result) {
        const currentSelectRow = deepClone(this.multipleSelectedList)
        this.list = this.list.map((element, index, array) => {
          const current = this.multipleSelectedList.filter((item) => item.orderId == element.orderId)
          if (current.length > 0) {
            if (this.singlEditForm.platformAccountId) {
              this.changePlatformAccountId(this.singlEditForm.platformAccountId)
            }
            if (this.singlEditForm.openInvoice == 0) {
              element.invoice = null
              element.taxpayer = null
              element.accountBank = null
              element.accountName = null
              element.projectName = null
              element.taxRate = null
              element.addressPhone = null
            }

            element = { ...element, ...this.singlEditForm }
          }
          this.$refs.multipleTable.toggleRowSelection(element, true)
          return element
        })
        this.$nextTick(() => {
          this.list.forEach((element) => {
            const current = currentSelectRow.filter((item) => item.orderId == element.orderId)
            if (current.length > 0) {
              this.$refs.multipleTable.toggleRowSelection(element, true)
            }
          })
          // currentSelectRow.forEach((element) => {
          //   this.$refs.multipleTable.toggleRowSelection(element, true)
          // })
        })
        this.handleCloseBefore()
      }
    },
    // 打开批量设置收款单信息弹窗
    setReceiptInfo() {
      if (this.multipleSelectedList.length == 0) {
        this.$modal.msgError(`请先选择需要批量处理的订单`)
        return
      }
      this.openBatchReceiptInfo = true
      this.$nextTick(() => {
        this.$refs["singlEditForm"].clearValidate()
      })
    },
    handleCloseBefore(el) {
      this.singlEditForm = {}
      this.$refs["singlEditForm"].clearValidate()
      this.$nextTick(() => {
        this.openSinglEditForm = false
        this.openBatchReceiptInfo = false //   批量设置收款单信息
        this.openSetsWhetherToInvoice = false // 批量设置是否开票
        this.openBatchInvoiceInfo = false
      })
    },
    //修改table样式
    tableRowClassName({ row, rowIndex }) {
      let current = this.selectStatusList.filter((item) => item == row.orderId)
      if (current.length > 0) {
        return "success-row"
      }
      return ""
    },
    async submitList() {
      let paramsList = this.list.filter((item) => {
        if (item.openInvoice == 0 || (item.openInvoice == 1 && item.invoice)) {
          return item
        }
      })
      if (paramsList.length != this.list.length) {
        this.$modal.msgError(`缺少生成收款单的必要的信息`)
        return
      }
      await this.$confirm(this.$t("确认提交修改？"), this.$t("提示"))
      await handleBankGNRTReceipt(paramsList)
      this.$modal.msgSuccess("修改成功")
      this.$router.go(-1)
    },
    openSingleEditDialog(row) {
      this.openSinglEditForm = true
      this.selectStatusList = [row.orderId]
      this.singlEditForm = deepClone(row)
      this.$nextTick(() => {
        this.$refs["singlEditForm"].clearValidate()
      })
    },
    async validateFormResult(formEl) {
      return await this.$refs[formEl].validate()
    },
    cancel() {
      this.singlEditForm = {}
      this.$refs["singlEditForm"].clearValidate()
      this.openSinglEditForm = false
      this.openBatchReceiptInfo = false //   批量设置收款单信息
      this.openSetsWhetherToInvoice = false // 批量设置是否开票
      this.openBatchInvoiceInfo = false
    },
    changePlatformAccountId(platformAccountId) {
      const bankInfo = this.bankData.filter((item) => item.id == platformAccountId)
      this.singlEditForm.platformAccountName = bankInfo[0].baAccountName
    },
    //单个编辑
    async submitSingleForm() {
      const result = await this.validateFormResult("singlEditForm")
      if (result) {
        if (this.singlEditForm.platformAccountId) {
          this.changePlatformAccountId(this.singlEditForm.platformAccountId)
        }

        let currentRow = deepClone(this.singlEditForm)
        let multipleRow = deepClone(this.multipleSelectedList)
        this.list = this.list.map((element, index, array) => {
          if (element.orderId == this.singlEditForm.orderId) {
            element = this.singlEditForm
          }
          return element
        })
        this.handleCloseBefore()
        this.openSinglEditForm = false
        this.$nextTick(() => {
          this.list.forEach((element) => {
            const current = multipleRow.filter((item) => item.orderId == element.orderId)
            if (current.length > 0) {
              this.$refs.multipleTable.toggleRowSelection(element, true)
            }
          })
          this.selectStatusList = [currentRow.orderId]
        })
      }
    },
    handleSelectionChange(val) {
      // this.$nextTick(() => {
      console.log("888", val)
      this.multipleSelectedList = val
      this.selectStatusList = val.map((item) => {
        return item.orderId
      })
      // })
    },
    getWareHouseLabel(id) {
      const houseItem = this.warehouseList.filter((item) => {
        return item.id == id
      })
      return houseItem.length > 0 ? this.$l(houseItem[0], "title") : "-"
    },
    loadOrderDataList() {
      this.loading = true
      loadBatGNRTReceiptList(this.queryParams).then((res) => {
        this.list = res.data.list
        this.loading = false
      })
    }
  }
}
</script>

<style lang="scss" scoped>
::v-deep .el-table .warning-row {
  background: oldlace;
}

::v-deep .el-table .success-row {
  background: #f0f9eb;
}
.title {
  padding: 20px 0;
  font-size: 18px;
  font-weight: bold;
}
.pad-t {
  padding: 10px 0;
}
.footer {
  display: flex;
  padding-top: 30px;
  justify-content: center;
}
.orderBox {
  padding-bottom: 10px;
  display: flex;
  .left {
    width: 160px;
  }
  .right {
    flex: 1;
  }
  .orderInfoItem {
    padding-bottom: 4px;
  }
}
</style>
