<template>
  <at-table
    @load="loadData"
    :data="data"
    :page-result="pageResult"
    ref="AtTable"
    :default-querys="[{property: 'pm.ID_', value: $route.params.id}]"
    :default-sorter="[{direction: 'DESC', property: 'contractDate'}]"
    :dialogTitle="dialogTitle"
    :dialogVisible="dialogVisible"
    :cellClassNameFn="cellClassNameFn"
    @select-all="handleSelect"
    @select="handleSelect"
    @handleDialogCancel="handleDialogCancel"
    @handleDialogClose="handleDialogCancel"
    @handleDialogSubmit="handleDialogSubmit"
    @row-dblclick="handleRowDBClick"
  >
    <template v-slot:searchInput>
      <el-form
        ref="searchForm"
        :model="searchForm"
        label-width="80px"
        class="search-top"
        @submit.native.prevent
      >
        <el-date-picker
          v-model="searchForm.contractDate"
          type="date"
          placeholder="选择计划日期"
          value-format="yyyy-MM-dd"
          format="yyyy-MM-dd"
          style="width: 100%"
          @keyup.enter.native="findinfo"
        >
        </el-date-picker>
        <dict-select
          dictCode="jdgl-yt"
          :hasDefaultOption="true"
          clearable
          placeholder="请选择费用名称"
          v-model="searchForm.purpose"
          style="width: 100%"
          @keyup.enter.native="findinfo"
        />
        <el-button
          size="small"
          @click="findinfo"
          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-form>
    </template>
    <template v-slot:operationBtn>
      <el-button
        size="small"
        type="primary"
        @click="handleAdd"
        icon="el-icon-plus"
        >添加</el-button
      >
      <ht-delete-button
        :url="deleteUrl"
        :requestMethod="'POST'"
        :htTable="$refs.AtTable"
        >删除</ht-delete-button
      >
      <import-file :importData="importData" @load="load"></import-file>
      <el-button
        size="small"
        type="primary"
        @click="handleExport"
        :loading="loading"
        icon="el-icon-download"
        plain
        style="margin-left: 10px"
        >导出</el-button
      >
      <el-button
        class="back"
        @click="handleBack"
        size="small"
        type="primary"
        icon="el-icon-back"
        plain
        >返回</el-button
      >
    </template>
    <template>
      <el-table-column type="selection" width="55" align="center">
      </el-table-column>
      <el-table-column type="index" label="序号" align="center" width="55">
      </el-table-column>
      <el-table-column
        prop="projectName"
        label="项目名称"
        align="center"
        :show-overflow-tooltip="true"
      >
      </el-table-column>
      <el-table-column
        prop="contractDate"
        label="计划日期"
        align="center"
        :show-overflow-tooltip="true"
      >
      </el-table-column>
      <el-table-column
        prop="purpose"
        label="费用名称"
        align="center"
        :show-overflow-tooltip="true"
      >
        <template v-slot="{row}">
          <span v-if="row.purpose !== '----'">
            {{ getDictName('jdgl-yt', row.purpose) }}
          </span>
          <span v-else>----</span>
        </template>
      </el-table-column>
      <el-table-column
        prop="unitNname"
        label="单位名称"
        align="center"
        :show-overflow-tooltip="true"
      >
      </el-table-column>
      <el-table-column
        prop="contractAmount"
        label="金额(万元)"
        align="center"
        :show-overflow-tooltip="true"
      >
      </el-table-column>
      <el-table-column
        prop="hasNew"
        label="是否本年度新开工项目"
        align="center"
        :show-overflow-tooltip="true"
      >
        <template v-slot="{row}">
          <el-tag
            v-if="row.hasNew !== '----'"
            :type="row.hasNew == '否' ? 'danger' : ''"
          >
            {{ row.hasNew }}
          </el-tag>
          <span v-else>----</span>
        </template>
      </el-table-column>
      <el-table-column
        prop="hasSpecial"
        label="是否本年度专项债申报项目"
        align="center"
        :show-overflow-tooltip="true"
      >
        <template v-slot="{row}">
          <el-tag
            v-if="row.hasSpecial !== '----'"
            :type="row.hasSpecial == '否' ? 'danger' : ''"
          >
            {{ row.hasSpecial }}
          </el-tag>
          <span v-else>----</span>
        </template>
      </el-table-column>
      <el-table-column
        prop="remarks"
        label="备注"
        align="center"
        width="100"
        :show-overflow-tooltip="true"
      >
      </el-table-column>
    </template>
    <template v-slot:dialogContent>
      <el-form
        ref="form"
        v-form
        data-vv-scope="form"
        :model="form"
        :rules="rules"
        label-width="130px"
        v-if="dialogVisible"
        v-loading.fullscreen="loading"
      >
        <el-row>
          <el-col :span="12">
            <el-form-item label="项目名称" prop="projectName">
              <el-input
                v-model="form.projectName"
                placeholder="请输入项目名称"
                clearable
                disabled
              >
                <el-button
                  disabled
                  type="primary"
                  @click="handleFocusProject"
                  slot="append"
                  icon="el-icon-search"
                ></el-button>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="单位名称" prop="unitNname">
              <el-input
                v-model="form.unitNname"
                placeholder="请输入单位名称"
                clearable
                disabled
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="费用名称" prop="purpose">
              <dict-select
                dictCode="jdgl-yt"
                clearable
                placeholder="请选择费用"
                v-model="form.purpose"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="计划日期" prop="contractDate">
              <el-date-picker
                v-model="form.contractDate"
                value-format="yyyy-MM"
                format="yyyy-MM"
                type="month"
                placeholder="请选择计划日期"
                style="width: 100%"
              >
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="金额" prop="contractAmount">
              <el-input
                v-model="form.contractAmount"
                placeholder="请输入金额"
                clearable
              >
                <i slot="suffix">万元</i>
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="是否本年度新开工项目" prop="hasNew">
              <el-select v-model="form.hasNew" placeholder="请选择">
                <el-option
                  v-for="item in options"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="是否本年度专项债申报项目" prop="hasSpecial">
              <el-select v-model="form.hasSpecial" placeholder="请选择">
                <el-option
                  v-for="item in options2"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="备注" prop="remarks">
          <el-input
            type="textarea"
            v-model="form.remarks"
            placeholder="请输入备注"
          >
          </el-input>
        </el-form-item>
        <file-table
          @handleFile="handleFile"
          :file="form.accessoryInfo"
          :info="'上传文件'"
          style="margin-top: 10px"
        />
      </el-form>
    </template>
    <template v-slot:showTotalData>
      <span class="show-slected">
        已选中<i>{{ selected.numbers }}</i>
        条数据， 金额合计
        <i>{{ moneyFormatter(selected.money) }} </i>万元
      </span>
    </template>
    <project-info-dialog
      ref="project"
      :single="true"
      @select="handleSelectProject"
    ></project-info-dialog>
  </at-table>
</template>
<script>
import ProjectInfoDialog from '@/components/dialog/ProjectInfoDialog.vue'
import utils from '@/utils.js'
import req from '@/request.js'
const BigNumber = require('bignumber.js')
export default {
  name: 'fundPlan',
  components: {
    ProjectInfoDialog,
  },
  data() {
    return {
      total: {
        projectName: '合计',
        contractDate: '----',
        purpose: '----',
        unitNname: '----',
        contractAmount: 0,
        hasNew: '----',
        hasSpecial: '----',
        remarks: '----',
      },
      selected: {
        numbers: 0,
        money: '0',
      },
      options: [
        {label: '是', value: '是'},
        {label: '否', value: '否'},
      ],
      options2: [
        {label: '是', value: '是'},
        {label: '否', value: '否'},
      ],
      searchForm: {
        purpose: '',
        contractDate: '',
      },
      rules: {},
      form: {},
      loading: false,
      dialogVisible: false,
      data: [],
      pageResult: {
        page: 1,
        pageSize: 20,
        total: 0,
      },
      dialogTitle: '添加',
      importData: {
        title: '资金计划导入',
        templateName: '资金计划模板.xls',
        downloadUrl: './../static/excel/fundPlan.xlsx',
        importUrl:
          window.context.cqxy + '/biz/contract/fundPlan/v1/importExcelData',
        projectId: '',
        contractId: '',
      },
      routerParams: null,
    }
  },
  mounted() {
    this.routerParams = JSON.parse(sessionStorage.getItem('routerParams'))
    this.importData.projectId = this.routerParams.project.id
    this.importData.contractId = this.routerParams.contract.id
  },
  computed: {
    deleteUrl() {
      return window.context.cqxy + '/biz/contract/fundPlan/v1/delete'
    },
  },
  methods: {
    handleFile(file) {
      this.form.accessoryInfo = file
    },
    //重置
    handleReset() {
      this.searchForm.purpose = ''
      this.searchForm.contractDate = ''
      this.$refs['searchForm'].resetFields()
      this.pageResult = {
        page: 1,
        pageSize: 20,
        total: 0,
      }
      this.$nextTick(() => {
        this.$refs.AtTable.load()
      })
    },
    load() {
      this.$refs.AtTable.load()
    },

    handleExport() {
      this.loading = true
      let params = {
        pageBean: {
          page: 1,
          pageSize: -1,
          showTotal: true,
        },
        querys: [
          {
            group: 'main',
            operation: 'EQUAL',
            parentGroup: '',
            property: 'pm.ID_',
            relation: 'AND',
            value: this.$route.params.id,
          },
          {
            group: 'main',
            operation: 'EQUAL',
            parentGroup: '',
            property: 'contract_id_',
            relation: 'AND',
            value: this.routerParams.contract.id,
          },
        ],
      }
      if (this.data.length > 0) {
        req
          .downloadPostCopy(
            '${cqxy}/biz/contract/fundPlan/v1/exportDataToExcel',
            params
          )
          .then((res) => {
            if (res.status === 200) {
              this.loading = false
              this.$message.success('导出成功')
            } else {
              this.loading = false
              this.$message.error('导出失败')
            }
          })
      } else {
        this.loading = false
        this.$message.warning('暂无数据导出')
      }
    },

    loadData(param, cb) {
      this.routerParams = JSON.parse(sessionStorage.getItem('routerParams'))
      let querys = []
      let search = {
        purpose_: this.searchForm.purpose,
        contract_date_: this.searchForm.contractDate,
      }
      for (let i in search) {
        if (search[i]) {
          querys.push({
            group: 'main',
            operation: 'EQUAL',
            property: i,
            relation: 'AND',
            value: search[i],
          })
        }
      }
      if (param.querys && param.querys.length) {
        param.querys.push(...querys)
      } else {
        param.querys = querys
      }
      this.$http
        .post('${cqxy}/biz/contract/fundPlan/v1/page', param)
        .then(
          (resp) => {
            let response = resp.data.value
            this.selected = {
              numbers: 0,
              money: '0',
            }
            let data = response.rows
            let total = this.calculationTotal(data, 'contractAmount')
            this.total.contractAmount = total
            data = data.map((item) => {
              item.projectName = this.$route.params.projectName
              return item
            })
            if (data.length !== 0) {
              data.push(this.total)
            }
            this.pageResult = {
              page: response.page,
              pageSize: response.pageSize,
              total: response.total,
            }
          },
          (error) => {
            reject(error)
          }
        )
        .finally(() => {
          if (cb) {
            cb()
          }
        })
    },
    findinfo() {
      this.$refs.AtTable.load()
    },
    handleAdd() {
      this.dialogVisible = true
      let date = new Date()
      this.form = {
        projectName: this.$route.params.projectName,
        projectId: this.$route.params.id,
        contractId: this.routerParams.contract.id,
        purpose: '',
        unitNname: this.routerParams.contract.secondParty,
        contractDate: utils.formatMothYear(date),
        contractAmount: '',
        hasNew: '',
        hasSpecial: '',
        remarks: '',
        accessoryInfo: [],
      }
    },
    handleSelect(selection) {
      selection.forEach((item, index) => {
        if (item.projectName === '合计') {
          selection.splice(index, 1)
        }
      })
      this.selected.numbers = selection.length
      let total = this.calculationTotal(selection, 'contractAmount')
      this.selected.money = total
    },
    handleFocusProject() {
      this.$refs.project.open()
    },
    handleSelectProject(data) {
      this.form.projectId = data.id
      this.form.projectInfo.projectCode = data.projectCode
      this.form.projectInfo.projectName = data.projectName
    },
    handleRowDBClick(data) {
      this.dialogVisible = true
      this.form = data
    },
    //保存
    handleDialogSubmit() {
      if (this.form.accessoryInfo && this.form.accessoryInfo.length > 0) {
        this.form.accessoryInfo.forEach((item) => {
          if (item.id) {
            delete item.id
          }
        })
      }
      this.$http
        .post('${cqxy}/biz/contract/fundPlan/v1/save', this.form)
        .then((res) => {
          if (res.data.state) {
            this.$message.success(res.data.message)
            this.$refs.AtTable.load()
            this.dialogVisible = false
          } else {
            this.$message.error(res.data.message)
          }
        })
    },
    handleDialogCancel() {
      this.dialogVisible = false
    },
    //返回
    handleBack() {
      this.$router.push({
        name: 'ProjectFlowChart',
        params: {
          id: this.$route.params.id,
          alias: this.routerParams.alias,
        },
      })
    },
    // 计算列表合同金额合计金额
    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';
.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>
