<template>
  <div class='container'  v-loading="loading">
    <el-container>
      <el-header>
        <div class="title">
          <span>资金复核日报</span>
          <el-date-picker v-model="days" value-format="yyyy-MM-dd" type="date" placeholder="选择日期"
                          @change="handleChangeDate">
          </el-date-picker>
        </div>
      </el-header>
      <el-main>
        <el-row>
          <el-col :span="12">
            <el-button icon="el-icon-download" @click="onSubmitDc">资金日报导出</el-button>
          </el-col>
          <el-col :span="12">
            <div style="text-align: right;">
              <el-checkbox v-model="updateInspStatusChecked" style="margin-right: 15px;">包含已复核</el-checkbox>
              <el-button type="warning" @click="onUpdateInspStatusName('不通过')">一键不通过</el-button>
              <el-button type="success" @click="onUpdateInspStatusName('通过')">一键通过</el-button>
            </div>
          </el-col>
        </el-row>
        <el-table :data="tableData" border :default-sort="{ prop: 'wdailyfundsfdate', order: '' }"
                  :span-method="spanMethod" :row-class-name="tableRowClassName"> style="width: 100%; margin-top: 20px">
          <el-table-column prop="fOrgType" align="center" label="公司类型" width="80"></el-table-column>
<!--          <el-table-column prop="fDate" align="center" sortable label="日期" width="120"></el-table-column>-->
          <el-table-column prop="fOrgName" align="center" label="公司"></el-table-column>
          <el-table-column prop="fYesterdayAccountBalance" align="center" label="昨日余额(元)"
                           width="120"></el-table-column>
          <el-table-column prop="fTodayAccountBalance" align="center" label="今日余额(元)" width="120"></el-table-column>
          <el-table-column prop="fAccountBalanceDifference" align="center" label="差额(今日-昨日)(元)"
                           width="160"></el-table-column>
          <el-table-column prop="fTodayNetCashFlow" align="center" label="净现金流(元)" width="120"></el-table-column>
          <el-table-column prop="fTodayFreezeAmount" align="center" label="冻结金额(元)" width="120"></el-table-column>
          <el-table-column prop="fTodayFreezing" align="center" label="冻结金额上限(元)" width="140"></el-table-column>
          <el-table-column prop="fInspStatusName" align="center" label="复核" width="120">
            <template slot-scope="scope">
              <template v-if="scope.row.id">
                <el-select v-model="scope.row.fInspStatusName" placeholder="请选择" style="width: 100%">
                  <el-option label="通过" value="通过"></el-option>
                  <el-option label="不通过" value="不通过"></el-option>
                </el-select>
              </template>
            </template>
          </el-table-column>
          <el-table-column prop="fInspNotes" align="center" label="备注" width="220">
            <template slot-scope="scope">
              <template v-if="scope.row.id">
                <el-input placeholder="请输入内容" v-model="scope.row.fInspNotes" clearable></el-input>
              </template>
            </template>
          </el-table-column>
        </el-table>
      </el-main>
      <el-footer>
        <div class="footerBtn" v-if="tableData.length">
          <el-button type="primary" style="width: 200px;" @click="handleReview" v-if="!isOn()">
            复核完成
          </el-button>
          <el-button type="info" style="width: 200px;" plain v-if="isOn()">
            复核完成
          </el-button>
        </div>
      </el-footer>
    </el-container>
  </div>
</template>
<script>
import {dailyFundsByDateExport, getInspList, updateInsps} from "@/api/service/dailyFunds";
import TemplateForm from "@/components/dataTemplate/TemplateForm.vue";

export default {
  components: {TemplateForm},
  data() {
    return {
      loading:false,
      updateInspStatusChecked: false,
      tableData: [],
      days: new Date(Date.now() - 86400000).toISOString().split('T')[0]
    };
  },
  mounted() {
    this.initData();
  },
  methods: {
    async initData() {
      let data = await getInspList(this.days);
      this.tableData = this.mergeTableRow(data.value, ['fOrgType']);
    },
    handleChangeDate() {
      this.initData();
    },
    spanMethod({row, column, rowIndex, columnIndex}) {
      if (column.property == 'fOrgType' && row.fOrgType != row.fDate) {
        return [row.fOrgTypeSPAN.rowspan, row.fOrgTypeSPAN.colspan]
      }
      if (row.fOrgType == row.fDate) {
        if (columnIndex == 0) {
          return [1, 2];
        } else if (columnIndex == 1) {
          return [0, 0];
        }
      }
    },
    mergeTableRow(data, merge) {
      if (!merge || merge.length === 0) {
        return data
      }
      merge.forEach((m) => {
        const mList = {}
        data = data.map((v, index) => {
          const rowVal = v[m]
          if (mList[rowVal] && mList[rowVal].newIndex === index) {
            mList[rowVal]['num']++
            mList[rowVal]['newIndex']++
            data[mList[rowVal]['index']][m + 'SPAN'].rowspan++
            v[m + 'SPAN'] = {
              rowspan: 0,
              colspan: 0
            }
          } else {
            mList[rowVal] = {num: 1, index: index, newIndex: index + 1}
            v[m + 'SPAN'] = {
              rowspan: 1,
              colspan: 1
            }
          }
          return v
        })
      })
      return data
    },
    tableRowClassName({row, rowIndex}) {
      if (!row.id && row.fOrgType != '汇总') {
        return 'hj-row';
      }
      if (!row.id && row.fOrgType == '汇总') {
        return 'hz-row';
      }
      return '';
    },
    // 复核
    handleReview() {
      this.$confirm('是否确认批量复核？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.loading=true;
        let wDailyFundsList = [];
        this.tableData.forEach(d => {
          if (d.id && d.fInspStatusName && d.fInspStatusName != '待复核') {
            wDailyFundsList.push({
              id: d.id,
              fDate: d.fDate + " 00:00:00",
              fOrgName: d.fOrgName,
              fOrgId: d.fOrgId,
              fOrgType: d.fOrgType,
              fInspStatusName: d.fInspStatusName,
              fInspNotes: d.fInspNotes
            })
          }
        })
        updateInsps({
          wDailyFundsList: wDailyFundsList
        }).then((res) => {
          if (res.state) {
            this.loading=false;
            this.$message.success(res.message)
            this.$emit("RefreshTable");
            this.dialogVisible = false;
          } else {
            this.loading=false;
            this.$emit("RefreshTable");
            this.$message.warning(res.message)
            this.dialogVisible = false;
          }
        })
      });
    },
    //是否可提交
    isOn() {
      let data = this.tableData.find(d => {
        return d.fInspStatusName == '待复核'
      })
      return data ? true : false;
    },
    // 导出
    onSubmitDc() {
      if (!this.days) {
        this.$message.error('请选择日期！');
        return false;
      }
      dailyFundsByDateExport(this.days).then(_ref => {
        let {data, headers} = _ref;
        // 附件下载
        const blob = new Blob([data]);
        // 附件下载
        const fileName = decodeURIComponent(headers['content-disposition'].split(';')[1].split('filename=')[1]);
        saveAs(blob, fileName);
      }).catch(err => {
        this.$message.error(`模板下载失败：${err}`);
      });
    },
    //修改状态
    onUpdateInspStatusName(status) {
      this.tableData.forEach(d => {
        if (this.updateInspStatusChecked) {
          d.fInspStatusName = status;
        } else {
          d.fInspStatusName = d.fInspStatusName == '待复核' ? status : d.fInspStatusName;
        }
      })
    }
  }

};
</script>
<style lang='scss' scoped>
.container {
  background: #fff;
}

.title {
  font-size: 28px;
  display: flex;
  justify-content: center;
  align-items: center;

  .el-input {
    line-height: 0;
  }

  ::v-deep .el-input__inner {
    border: none;
    font-size: 28px;
  }
}


.el-header {
  text-align: center;
  line-height: 60px;
}

.el-footer {
  width: 100%;
}

.footerBtn {
  display: flex;
  justify-content: center;
  position: fixed;
  //left: 208px;
  //right: 208px;
  bottom: 10px;
  width: 100%;
  background-color: #f4f4f4;
  left: 0;
  right: 0;
}


::v-deep {
  .el-table .hj-row {
    background-color: #f4f4f4;
    font-weight: bold;
  }

  .el-table .hz-row {
    font-weight: bold;
  }
}
</style>
