<!--
 * @Author: @liulin
 * @Date: 2022-06-02 15:02:58
 * @LastEditors: Please set LastEditors
-->
<template>
  <div>
    <at-table
      @load="loadData"
      :data="data"
      :page-result="pageResult"
      ref="AtTable"
      :default-sorter="[
        {direction: 'ASC', property: 'pr.PROJECT_ID_'},
        {direction: 'ASC', property: 'pr.CONTRACT_ID_'},
        {direction: 'DESC', property: 'pr.REGISTER_DATE_'},
      ]"
      :cellClassNameFn="cellClassNameFn"
      @select-all="handleSelect"
      @select="handleSelect"
      @row-dblclick="handleRowDBClick"
      :justShowSearch="justShowSearch"
    >
      <template v-slot:searchInput>
        <el-form
          ref="searchForm"
          :model="searchForm"
          label-width="80px"
          class="search-top"
          @submit.native.prevent
        >
          <el-select
            v-if="isShow"
            v-model="searchForm.createTime"
            clearable
            placeholder="请选择年份"
            @change="handleSearch"
          >
            <el-option
              v-for="item in optionYears"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
          <dict-select
            v-if="isShow"
            v-model="searchForm.projectType"
            dictCode="xmgl-xmlx"
            validate="required"
            placeholder="请选择项目类型"
            :clearable="true"
            @input="handleSearch"
          />
          <el-input
            v-if="isShow"
            v-model="searchForm.projectName"
            style="width: 100%"
            placeholder="请输入项目名称"
            @input="handleSearch"
          ></el-input>
          <dict-select
            v-if="!isShow"
            dictCode="jdgl-yt"
            :hasDefaultOption="true"
            :filterable="true"
            clearable
            placeholder="请选择用途"
            v-model="searchForm.purpose"
            @input="handleSearch"
            style="width: 100%"
          />
          <!-- <el-input
          v-if="!isShow"
            v-model="searchForm.contractName"
            placeholder="请输入合同名称"
            clearable
            @keyup.enter.native="handleSearch"
          ></el-input> -->
          <el-button
            size="small"
            @click="handleSearch"
            type="primary"
            class="el-icon-search search-btn"
            >查询</el-button
          >
          <el-button
            size="small"
            @click="handleReset"
            type="primary"
            plain
            class="el-icon-refresh"
            >重置</el-button
          >
          <el-button
            size="small"
            type="primary"
            @click="handleExport"
            :loading="loading"
            icon="el-icon-download"
            plain
            style="margin-left: 10px"
            >导出</el-button
          >
        </el-form>
      </template>
      <template v-slot:seacrhMoreInput v-if="isShow">
        <div class="moreInput">
          <el-date-picker
            unlink-panels
            v-model="searchForm.yearMonth"
            value-format="yyyy-MM"
            type="monthrange"
            range-separator="至"
            start-placeholder="审批日期"
            end-placeholder="审批日期"
            @change="handleSearch"
          >
          </el-date-picker>
        </div>
      </template>
      <template v-slot:operationBtn>
        <div class="yearTotal">
          <!-- <div>年度总投资：<span class="textRed">{{payTotal}}</span>万元</div> -->
          <div>
            {{ currentYear }}年度总支付：<span class="textRed">{{
              investTotal
            }}</span
            >元
          </div>
        </div>
      </template>
      <template>
        <!-- <el-table-column type="selection" width="55" align="center">
        </el-table-column> -->
        <el-table-column type="index" label="序号" width="55" align="center">
        </el-table-column>
        <el-table-column
          prop="projectName"
          label="项目名称"
          align="center"
          :show-overflow-tooltip="true"
        >
        </el-table-column>
        <!-- <el-table-column
          prop="changeName"
          label="变更名称"
          align="center"
          :show-overflow-tooltip="true"
        >
        </el-table-column> -->
        <ht-table-column
          prop="amountAppropriated"
          label="已拨款额（元）"
          align="center"
          width="140"
          :show-overflow-tooltip="true"
        >
        </ht-table-column>
        <el-table-column
          prop="contractAmount"
          label="合同金额（元）"
          align="center"
          width="140"
          :show-overflow-tooltip="true"
        >
        </el-table-column>
        <el-table-column
          prop="contractName"
          label="合同名称"
          align="center"
          :show-overflow-tooltip="true"
        >
        </el-table-column>
        <el-table-column
          prop="payRatio"
          label="累计支付比例"
          align="center"
          width="130"
          :show-overflow-tooltip="true"
        >
        </el-table-column>
        <!-- <el-table-column
          prop="payType"
          label="支付方式"
          align="center"
          width="160"
          :show-overflow-tooltip="true"
        >
        </el-table-column> -->
        <el-table-column
          prop="payeeAmountTotal"
          label="本次拨付金额（元）"
          align="center"
          width="170"
          :show-overflow-tooltip="true"
        >
        </el-table-column>
        <el-table-column
          prop="purpose"
          label="用途"
          align="center"
          width="100"
          :show-overflow-tooltip="true"
        >
        </el-table-column>
        <el-table-column
          prop="registerDate"
          label="审批日期"
          align="center"
          width="100"
          :show-overflow-tooltip="true"
        >
        </el-table-column>
        <el-table-column
          prop="registerPersonName"
          label="收款单位"
          align="center"
          width="100"
          :show-overflow-tooltip="true"
        >
        </el-table-column>
      </template>
      <!-- 弹框 -->
      <!-- <template v-slot:dialogContent> </template> -->
    </at-table>
    <el-dialog
      title="详情"
      :visible.sync="dialogVisible"
      width="1000px"
      top="8vh"
    >
      <div class="mainBox">
        <table>
          <tr>
            <td class="bgColor" style="width: 150px">项目名称</td>
            <td style="width: 240px">{{ details.projectName }}</td>
            <td class="bgColor" style="width: 150px">合同名称</td>
            <td style="width: 240px">{{ details.contractName }}</td>
          </tr>
          <tr>
            <td class="bgColor">合同金额（元）</td>
            <td>{{ details.contractAmount }}</td>
            <td class="bgColor">已拨款额（元）</td>
            <td>{{ details.amountAppropriated }}</td>
          </tr>
          <tr>
            <td class="bgColor">累计支付比例</td>
            <td>{{ details.payRatio }}</td>
            <!-- <td class="bgColor">支付方式</td>
            <td>{{ details.payType }}</td> -->
            <td class="bgColor">本次拨付金额（元）</td>
            <td>
              {{ details.payeeAmountTotal }}
            </td>
          </tr>
          <tr>
            <td class="bgColor">用途</td>
            <td>
              {{ details.purpose }}
            </td>
            <td class="bgColor">审批日期</td>
            <td>
              {{ details.registerDate }}
            </td>
          </tr>
          <tr>
            <td class="bgColor">收款单位</td>
            <td colspan="3">
              {{ details.registerPersonName }}
            </td>
          </tr>
        </table>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="dialogVisible = false"
          >关闭</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>
<script>
import req from '@/request.js'
const BigNumber = require('bignumber.js')
export default {
  name: 'paymentAccount',
  props: {
    pid: {
      type: String,
      default: '',
    },
    isShow: {
      type: Boolean,
      default: true,
    },
    alias: {
      type: String,
      default: '',
    },
  },
  data() {
    return {
      total: {
        projectName: '合计',
        amountAppropriated: 0,
        contractAmount: 0,
        contractName: '----',
        payRatio: '----',
        payeeAmountTotal: 0,
        purpose: '----',
        registerDate: '----',
        registerPersonName: '----',
      },
      justShowSearch: this.isShow,
      url: '',
      size: 'medium',
      loading: false,
      searchForm: {
        projectName: '', //项目名称
        createTime: new Date().getFullYear(), //当前年份
        projectType: '', //项目类型
        purpose: '',
      },
      optionYears: [], //顶部搜索年份选择数组
      details: {
        projectInfo: {},
      },
      data: [],
      pageResult: {
        page: 1,
        pageSize: 20,
        total: 0,
      },
      form: {},
      dialogVisible: false,
      investTotal: 0,
    }
  },
  created() {
    this.getYear()
    this.getYearTotal()
  },
  methods: {
    getYearTotal() {
      if (this.searchForm.createTime && this.searchForm.createTime != '') {
        let formData = new FormData()
        formData.append('year', this.searchForm.createTime)
        this.$http
          .post('${cqxy}/biz/ledger/pay/v1/totalPayByYear', formData)
          .then((res) => {
            let data = res.data.value
            //  this.payTotal=data.payTotal
            this.investTotal = res.data.value
          })
      } else {
        let formData = new FormData()
        formData.append('year', 0)
        this.$http
          .post('${cqxy}/biz/ledger/pay/v1/totalPayByYear', formData)
          .then((res) => {
            this.investTotal = res.data.value
            this.currentYear = null
          })
      }
    },
    //获取顶部搜索的年份区间
    getYear() {
      const myDate = new Date()
      this.currentYear = myDate.getFullYear()
      this.beforeYear = this.currentYear - 1
      const startYear = 2006 //起始年份
      const endYear = myDate.getFullYear() //结束年份
      for (let i = endYear; i >= startYear; i--) {
        this.optionYears.push({
          label: i + '年',
          value: i,
        })
      }
    },
    handleReset() {
      this.searchForm.projectName = ''
      this.searchForm.createTime = ''
      this.searchForm.projectType = ''
      this.searchForm.purpose = ''
      this.$refs['searchForm'].resetFields()
      this.pageResult = {
        page: 1,
        pageSize: 20,
        total: 0,
      }
      this.$nextTick(() => {
        this.$refs.AtTable.load()
      })
    },
    //导出
    handleExport() {
      this.loading = true
      let query = []
      let search = {
        'pm.PROJECT_NAME_': this.searchForm.projectName,
        project_type_: this.searchForm.projectType,
        CREATE_TIME_: this.searchForm.createTime,
        year_month_: this.searchForm.yearMonth,
      }
      if (!this.isShow) {
        search['pm.ID_'] = this.pid
        ;(search.purpose_ = this.searchForm.purpose), delete search.CREATE_TIME_
      }
      for (let i in search) {
        if (search[i]) {
          if (i == 'CREATE_TIME_') {
            query.push(
              {
                group: 'createTimeGroup',
                operation: 'BETWEEN',
                parentGroup: '',
                property: 'commencement_time_',
                relation: 'OR',
                value: [
                  `${search[i]}-01-01 00:00:00`,
                  `${search[i]}-12-31 23:59:59`,
                ],
              }
              // {
              //   group: 'createTimeSubGroup',
              //   operation: 'LESS_EQUAL',
              //   parentGroup: 'createTimeGroup',
              //   property: 'commencement_time_',
              //   relation: 'AND',
              //   value: `${search[i]}-12-31 23:59:59`,
              // },
              // {
              //   group: 'createTimeSubGroup',
              //   operation: 'LESS',
              //   parentGroup: 'createTimeGroup',
              //   property: 'PROJECT_STATUS_',
              //   relation: 'AND',
              //   value: '12',
              // }
            )
          } else if (i == 'year_month_') {
            let lastDate = search[i][1]
            let str = lastDate.split('-')
            let year = parseInt(str[0])
            let month = parseInt(str[1])
            let date = new Date(year, month, 0).getDate()
            let arr = [`${search[i][0]}-01`, `${search[i][1]}-${date}`]
            console.log(arr)
            query.push({
              group: 'createTimeGroup',
              operation: 'BETWEEN',
              parentGroup: '',
              property: 'register_date_',
              relation: 'OR',
              value: arr,
            })
          } else if (i == 'pm.PROJECT_NAME_') {
            query.push({
              group: 'advance',
              operation: 'LIKE',
              property: i,
              relation: 'AND',
              value: search[i],
            })
          } else {
            query.push({
              group: 'advance',
              operation: 'EQUAL',
              property: i,
              relation: 'AND',
              value: search[i],
            })
          }
        }
      }
      let param = {
        pageBean: {
          page: 1,
          pageSize: -1,
          showTotal: true,
        },
        querys: query,
        sorter: [
          {
            direction: 'ASC',
            property: 'pr.PROJECT_ID_',
          },
          {
            direction: 'ASC',
            property: 'pr.CONTRACT_ID_',
          },
          {
            direction: 'DESC',
            property: 'pr.REGISTER_DATE_',
          },
        ],
      }
      req
        .downloadPostCopy('${cqxy}/biz/ledger/pay/v1/exportDataToExcel', param)
        .then((res) => {
          if (res.status == 200) {
            this.loading = false
            this.$message.success('导出成功')
          } else {
            this.loading = false
            this.$message.error('导出失败')
          }
        })
    },

    //查询
    handleSearch() {
      this.$refs.AtTable.load()
    },
    handleRowDBClick(data) {
      console.log(data)
      this.dialogVisible = true
      this.details = data
    },
    // handleDict(val, obj, str) {
    //   console.log('val:'+val,'obj:'+obj.name,'str:'+str)
    //   // if (str === 'jdgl-yt') {
    //   //   this.searchForm.purpose = obj.name
    //   // }
    // },
    handleSelect(selection) {},
    loadData(param, cb) {
      if (this.isShow) {
        // this.$refs.projectInfo.getProjectData(this.searchForm.createTime)
      }
      let query = []
      let search = {
        'pm.PROJECT_NAME_': this.searchForm.projectName,
        project_type_: this.searchForm.projectType,
        CREATE_TIME_: this.searchForm.createTime,
        year_month_: this.searchForm.yearMonth,
      }
      if (!this.isShow) {
        search['pm.ID_'] = this.pid
        ;(search.purpose_ = this.searchForm.purpose), delete search.CREATE_TIME_
      }
      for (let i in search) {
        if (search[i]) {
          if (i == 'CREATE_TIME_') {
            this.currentYear = this.searchForm.createTime
            this.beforeYear = this.currentYear - 1
            query.push(
              {
                group: 'createTimeGroup',
                operation: 'BETWEEN',
                parentGroup: '',
                property: 'commencement_time_',
                relation: 'OR',
                value: [
                  `${search[i]}-01-01 00:00:00`,
                  `${search[i]}-12-31 23:59:59`,
                ],
              }
              // {
              //   group: 'createTimeSubGroup',
              //   operation: 'LESS_EQUAL',
              //   parentGroup: 'createTimeGroup',
              //   property: 'register_date_',
              //   relation: 'AND',
              //   value: `${search[i]}-12-31 23:59:59`,
              // },
              // {
              //   group: 'createTimeSubGroup',
              //   operation: 'LESS',
              //   parentGroup: 'createTimeGroup',
              //   property: 'PROJECT_STATUS_',
              //   relation: 'AND',
              //   value: '12',
              // }
            )
          } else if (i == 'year_month_') {
            let lastDate = search[i][1]
            let str = lastDate.split('-')
            let year = parseInt(str[0])
            let month = parseInt(str[1])
            let date = new Date(year, month, 0).getDate()
            let arr = [`${search[i][0]}-01`, `${search[i][1]}-${date}`]
            query.push({
              group: 'createTimeGroup',
              operation: 'BETWEEN',
              parentGroup: '',
              property: 'register_date_',
              relation: 'OR',
              value: arr,
            })
          } else if (i == 'pm.PROJECT_NAME_') {
            query.push({
              group: 'advance',
              operation: 'LIKE',
              property: i,
              relation: 'AND',
              value: search[i],
            })
          } else {
            query.push({
              group: 'advance',
              operation: 'EQUAL',
              property: i,
              relation: 'AND',
              value: search[i],
            })
          }
        }
      }
      if (param.querys && param.querys.length) {
        param.querys.push(...query)
      } else {
        param.querys = query
      }
      this.$http
        .post('${cqxy}/biz/ledger/pay/v1/page', param)
        .then(
          (resp) => {
            let response = resp.data.value
            let data = response.rows
            this.total.amountAppropriated = this.calculationTotal(data, 'amountAppropriated')
            this.total.contractAmount = this.calculationTotal(data, 'contractAmount')
            this.total.payeeAmountTotal = this.calculationTotal(data, 'payeeAmountTotal')
            if (data.length !== 0) {
              data.push(this.total)
            }
            this.data = data
            // console.log(response, 'response')

            this.pageResult = {
              page: response.page,
              pageSize: response.pageSize,
              total: response.total,
            }
            this.getYearTotal()
          },
          (error) => {
            reject(error)
          }
        )
        .finally(() => cb())
    },
    // 计算列表合同金额合计金额
    calculationTotal(data, key) {
      let total = new BigNumber(0)
      if (key && data && data.length !== 0) {
        data.forEach((item) => {
          if (item[key]) {
            total = total.plus(item[key])
          } else {
            total = total.plus(0)
          }
        })
      }
      return this.moneyFormatter(total)
    },
    cellClassNameFn(row) {
      // 列表项目名称为【合计】隐藏复选框
      if (row.row.projectName === '合计') {
        return 'table-column-hidden'
      }
    },
  },
}
</script>
<style lang="scss" scoped>
@import '@/assets/css/common.scss';

/deep/ .el-input__suffix > .el-input__icon {
  display: none;
}
/deep/ .el-table--border th .cell {
  color: #000;
}

/deep/ .el-dialog__body {
  padding-top: 20px;
  padding-bottom: 20px;
}
table {
  width: 100%;
  border-collapse: collapse;
}

table,
table tr td {
  border: 1px solid #ebeef5;
}

table tr td {
  padding: 15px 10px;
  // text-align: center;
}
.bgColor {
  background: #fafafa;
  color: #909399;
  width: 150px;
}
/deep/ .el-table thead.is-group th {
  border-color: #ebeef5;
}
.yearTotal {
  display: flex;
  width: 100%;
  justify-content: flex-end;
  div {
    padding: 0 20px;
  }
}
.textRed {
  color: red;
  padding-right: 5px;
}
.show-slected {
  font-size: 18px;
  i {
    font-style: normal;
    font-weight: 700;
    margin: 0 5px;
    color: #f40;
  }
}
/deep/ .table-column-hidden .el-checkbox__input {
  display: none
}
/deep/ .table-column-hidden .cell > div {
  display: none
}
</style>
