<template>
  <div class="app-container">
    <el-card>
      <!--<el-select v-model="entryNameValue" filterable placeholder="项目名称" style="margin: 3px 10px;width: 180px " size="small" clearable>-->
      <!--<el-option-->
      <!--v-for="item in entryName"-->
      <!--:key="item.value"-->
      <!--:label="item.label"-->
      <!--:value="item.value"/>-->
      <!--</el-select>-->
      <el-input v-model="customerName" clearable size="small" style="width:220px;" placeholder="客户名称/项目名称/合同编号"/>
      <el-select v-show="false" v-model="customerName" filterable placeholder="请输入客户名称" style="margin: 3px;width: 220px " size="small" clearable>
        <el-option
          v-for="item in customerNames"
          :key="item.value"
          :label="item.label"
          :value="item.value"/>
      </el-select>
      <span style="font-size: 13px;margin-left: 10px">签订日期</span>
      <el-date-picker
        v-model="dateRange"
        :picker-options="pickerOptions"
        size="small"
        type="daterange"
        align="center"
        style="width: 240px;margin: 3px 0"
        value-format="yyyy-MM-dd"
        format="yyyy-MM-dd"
        range-separator="～"
        start-placeholder="开始日期"
        end-placeholder="结束日期"/>
      <el-button type="primary" icon="el-icon-search" size="small" style="margin-left: 10px" plain @click="PageSize = 30;PageCurrent = 1;tableData2=[];getTableData()">查询</el-button>
      <el-tooltip :open-delay="1200" effect="dark" content="导出" placement="top">
        <div style="display: inline-block">
          <el-button type="primary" plain class="el-icon-download" size="small" style="margin: 10px 0 0 250px" @click="exportExcel">导出</el-button>
        </div>
      </el-tooltip>
      <!--<el-badge :value="value" :max="99" class="item">-->
      <!--<el-button size="small" plain @click="AccountsReceivable">查看收款信息</el-button>-->
      <!--</el-badge>-->
    </el-card>
    <el-card>
      <el-col :span="17">
        <el-table
          v-loading="listLoading"
          :row-key="getRowKeys"
          :expand-row-keys="expands"
          :header-cell-style="{fontFamily:'YouYuan',fontSize:'13px',fontWeight:200}"
          :data="tableData1"
          style="width: 970px;"
          height="600px"
          highlight-current-row
          border
          stripe
          size="mini"
          @sort-change="sortChange"
          @row-click="getTableData2">
          <!--@expand-change="selectMachine"-->
          <!--<el-table-column type="expand" label="详情" width="50">-->
          <!--<template slot-scope="scope">-->
          <!--<el-table :data="tableData3" class="subTableHeader" border stripe style="width: 600px; text-align: center" size="mini">-->
          <!--<el-table-column label="发货单号" align="center" >-->
          <!--<template slot-scope="scope">-->
          <!--{{ scope.row.发货单号 }}-->
          <!--</template>-->
          <!--</el-table-column>-->
          <!--<el-table-column label="发货日期" align="center">-->
          <!--<template slot-scope="scope">-->
          <!--{{ scope.row.发货日期 }}-->
          <!--</template>-->
          <!--</el-table-column>-->
          <!--<el-table-column label="运输状态" align="center">-->
          <!--<template slot-scope="scope">-->
          <!--{{ parseInt(scope.row.运输状态) === 0 ? '运输中' : '已签收' }}-->
          <!--</template>-->
          <!--</el-table-column>-->
          <!--</el-table>-->
          <!--</template>-->
          <!--</el-table-column>-->
          <el-table-column align="center" label="合同编号" prop="合同编号" sortable="custom" width="118">
            <template slot-scope="scope">
              {{ scope.row.合同编号 }}
            </template>
          </el-table-column>
          <el-table-column align="center" label="项目名称" prop="项目名称" width="118" show-overflow-tooltip>
            <template slot-scope="scope">
              {{ scope.row.项目名称 }}
            </template>
          </el-table-column>
          <el-table-column align="center" label="客户名称" prop="客户名称" width="160" show-overflow-tooltip>
            <template slot-scope="scope">
              {{ scope.row.客户名称 }}
            </template>
          </el-table-column>
          <el-table-column align="center" label="付款方式" width="78">
            <template slot-scope="scope">
              {{ scope.row.付款方式 }}
            </template>
          </el-table-column>
          <el-table-column align="right" label="合同金额(万元)" prop="合同总金额" width="120" show-overflow-tooltip>
            <template slot-scope="scope">
              {{ Number(scope.row.合同总金额).toFixed(2) }}
            </template>
          </el-table-column>
          <el-table-column align="right" label="已收(万元)" prop="已支付" width="100" show-overflow-tooltip>
            <template slot-scope="scope">
              {{ Number(scope.row.已收金额).toFixed(2) }}
            </template>
          </el-table-column>
          <el-table-column align="right" label="未收(万元)" prop="未支付金额" width="100" show-overflow-tooltip>
            <template slot-scope="scope">
              {{ Number(scope.row.未收金额).toFixed(2) }}
            </template>
          </el-table-column>
          <el-table-column align="center" label="营销经理" prop="姓名" width="80">
            <template slot-scope="scope">
              {{ scope.row.姓名 }}
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" width="66">
            <template slot-scope="scope">
              <el-button type="text" size="mini" icon="el-icon-circle-plus-outline" @click.stop="addMoney(scope.row)">收款</el-button>
            </template>
          </el-table-column>
          <!--<el-table-column label="操作" align="center" width="60" fixed="right">-->
          <!--<template slot-scope="scope">-->
          <!--<el-tooltip :open-delay="1000" effect="dark" content="编辑" placement="top">-->
          <!--<div style="display: inline-block">-->
          <!--<el-button-->
          <!--:disabled="scope.row.是否禁用编辑"-->
          <!--type="text"-->
          <!--size="mini"-->
          <!--icon="el-icon-edit-outline"-->
          <!--@click.stop="EditTableData(scope.row)"/>-->
          <!--</div>-->
          <!--</el-tooltip>-->
          <!--<el-tooltip :open-delay="1000" effect="dark" content="新增发票" placement="top">-->
          <!--<div style="display: inline-block">-->
          <!--<el-button-->
          <!--:disabled="scope.row.是否禁用编辑"-->
          <!--type="text"-->
          <!--size="mini"-->
          <!--icon="el-icon-circle-plus-outline"-->
          <!--@click.stop="EditTableData(scope.row)"/>-->
          <!--</div>-->
          <!--</el-tooltip>-->
          <!--&lt;!&ndash;<el-tooltip :open-delay="1000" effect="dark" content="删除" placement="top">&ndash;&gt;-->
          <!--&lt;!&ndash;<div style="display: inline-block">&ndash;&gt;-->
          <!--&lt;!&ndash;<el-button&ndash;&gt;-->
          <!--&lt;!&ndash;style="margin-left: 20px"&ndash;&gt;-->
          <!--&lt;!&ndash;size="mini"&ndash;&gt;-->
          <!--&lt;!&ndash;type="text"&ndash;&gt;-->
          <!--&lt;!&ndash;icon="el-icon-delete"&ndash;&gt;-->
          <!--&lt;!&ndash;@click.stop="dellist(scope.row)"/>&ndash;&gt;-->
          <!--&lt;!&ndash;</div>&ndash;&gt;-->
          <!--&lt;!&ndash;</el-tooltip>&ndash;&gt;-->
          <!--</template>-->
          <!--</el-table-column>-->
        </el-table>
        <div class="block">
          <el-pagination
            :current-page="PageCurrent"
            :page-sizes="[10, 20, 30, 40]"
            :page-size="PageSize"
            :total="total"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"/>
        </div>
      </el-col>
      <el-col :span="7">
        <el-table
          :data="tableData2"
          :summary-method="getSummaries1"
          :header-cell-style="{fontFamily:'YouYuan',fontSize:'13px',fontWeight:200}"
          style="width: 395px;max-height: 440px;text-align: center"
          highlight-current-row
          show-summary
          border
          size="mini">
          <el-table-column
            align="center"
            label="序号"
            type="index"
            width="70"/>
          <el-table-column align="right" label="收款金额(万元)" width="120" prop="收款金额">
            <template slot-scope="scope">
              <template v-if="scope.row.edit">
                <el-input v-model="scope.row.收款金额" :min="0" style="width:100px" clearable size="mini"/>
              </template>
              <span v-else>{{ Number(scope.row.收款金额).toFixed(2) }}</span>
            </template>
          </el-table-column>
          <el-table-column label="收款时间" align="center" width="85" prop="收款时间">
            <template slot-scope="scope">
              {{ scope.row.收款时间 ? scope.row.收款时间.split(' ')[0] : '-' }}
            </template>
          </el-table-column>
          <el-table-column align="center" label="操作" width="100">
            <template slot-scope="scope">
              <el-button v-if="scope.row.edit" type="text" size="mini" icon="el-icon-circle-check-outline" @click="updateMoney(scope.row, scope.$index)">确定</el-button>
              <el-button v-if="scope.row.edit" class="cancel-btn" size="mini" type="text" @click="cancelEdit(scope.$index, scope.row)">取消</el-button>
              <el-button v-else type="text" size="mini" icon="el-icon-edit" @click="scope.row.edit=!scope.row.edit"/>
              <el-button v-if="!scope.row.edit" type="text" size="mini" icon="el-icon-delete" @click="deleteMoney(scope.row)"/>
            </template>
          </el-table-column>
        </el-table>
      </el-col>
    </el-card>
  </div>
</template>

<script>
import elInput from 'element-ui/packages/input'
import { getNowShotTime } from '@/utils/tool'
import { updateMoney, addMoney, deleteMoney, executionProgressID, getcustomername, searchProjectNumber2, AccountsReceivable, selectProvince, SelectMarketingManager, searchTable1, searchTable2, searchProjectNumber, PaymentPhase, selectMachine, downloadexcel } from '@/api//MarketingCenter/ContractCapitalManagement'

export default {
  components: {
    elInput
  },
  data() {
    return {
      dateRange: '',
      check1: '',
      pickerOptions: {
        shortcuts: [{
          text: '上季度',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(end.getTime() - 3600 * 1000 * 24 * 30 * 3)
            picker.$emit('pick', [start, end])
          }
        }, {
          text: '过去半年',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(end.getTime() - 3600 * 1000 * 24 * 366 / 2)
            picker.$emit('pick', [start, end])
          }
        }, {
          text: '过去一年',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(end.getTime() - 3600 * 1000 * 24 * 365)
            picker.$emit('pick', [start, end])
          }
        }]
      },
      customerNames: [],
      customerName: '',
      timetime: '',
      name: '',
      moneyValue: '',
      visible1: false,
      visible2: false,
      plannedTime: [],
      entryName2: [],
      count1: 0,
      type: '',
      value: null,
      selectMax: '',
      flag: '',
      title: '',
      editFukuan: '',
      ProvinceValue: '',
      Province: [],
      tableData3: [],
      tableData4: [],
      entryNameValue: '',
      entryName: [],
      peoplename: '',
      peopleid: '',
      dataPeople: [],
      ListPeople: [],
      list1: [], // 项目名称临时存储
      Planning: [],
      MarketingManagerValue: '', // 营销经理下拉框
      listLoading: false,
      listLoading2: false,
      tableData1: [],
      tableData2: [],
      gridData: [],
      expands: [],
      PageCurrent: 1,
      PageSize: 30,
      total: null,
      PageCurrent2: 1,
      PageSize2: 30,
      total2: null,
      maxMoney: 0, // 批次付款最大数额
      zijinID: '', // 资金ID
      PaymentPhase: [],
      temp: null,
      moneyID: '',
      projectCode: '',
      contractNumber: [],
      num: '',
      contractTotal: '',
      dialogFormVisiblePeople: false,
      AccountsReceivableVisible: false
    }
  },
  created() {
    this.getTableData()
    this.init()
    this.getCustomerName()
  },
  methods: {
    formatJson(filterVal, jsonData) {
      return jsonData.map(v => filterVal.map(j => {
        return v[j]
      }))
    },
    exportExcel() {
      this.dateRange ? this.check1 = 1 : (this.check1 = 0, this.dateRange = '')
      downloadexcel(this.entryNameValue, this.peopleid, this.customerName, this.check1, this.dateRange[0], this.dateRange[1], this.ordername, this.order).then(val => {
        for (let i = 0; i < val.data.length; i++) {
          val.data[i]['合同总金额(万元)'] === null ? val.data[i]['合同总金额(万元)'] = '0.00' : val.data[i]['合同总金额(万元)'] = (val.data[i]['合同总金额(万元)']).toFixed(2)
          val.data[i]['到账金额(万元)'] === null ? val.data[i]['到账金额(万元)'] = '0.00' : val.data[i]['到账金额(万元)'] = (val.data[i]['到账金额(万元)']).toFixed(2)
          val.data[i]['未收金额(万元)'] === null ? val.data[i]['未收金额(万元)'] = '0.00' : val.data[i]['未收金额(万元)'] = (val.data[i]['未收金额(万元)']).toFixed(2)
        }
        if (val.length !== 0) {
          import('@/vendor/Export2Excel').then(excel => {
            const tHeader = ['合同编号', '项目名称', '客户名称', '付款方式', '合同签订日期', '合同金额(万元)', '已收(万元)', '未收(万元)', '营销经理']
            const filterVal = ['合同编号', '项目名称', '客户名称', '付款方式', '合同签订日期', '合同总金额(万元)', '到账金额(万元)', '未收金额(万元)', '营销经理']
            const list = val.data
            const data = this.formatJson(filterVal, list)
            excel.export_json_to_excel({
              header: tHeader,
              data,
              filename: '合同收款计划' + getNowShotTime(),
              autoWidth: true,
              bookType: 'xlsx'
            })
          })
        } else {
          this.$message.warning('没有导出内容')
        }
      })
    },
    // 2020 02 20 刘路加新增排序
    sortChange(column, prop, order) {
      console.log(column + '-' + column.prop + '-' + column.order, 11111)
      if (column.prop === '合同编号') {
        this.ordername = 1
      } else if (column.prop === '合同总金额') {
        this.ordername = 2
      } else if (column.prop === '已支付') {
        this.ordername = 3
      } else if (column.prop === '未支付金额') {
        this.ordername = 4
      } else {
        this.ordername = ''
      }
      if (column.order === 'ascending') {
        this.order = 1
      } else if (column.order === 'descending') { this.order = 2 } else {
        this.order = ''
      }
      this.getTableData()
    },
    // 2020 02 18 刘路加新增合计
    getSummaries1: function(param) {
      const { columns, data } = param
      const sums = []
      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = '合计'
          return
        } else if (index === 1) {
          const values = data.map(item => Number(parseFloat(item['收款金额'])))
          if (!values.every(value => isNaN(value))) {
            sums[index] = values.reduce((prev, curr) => {
              const value = Number(curr)
              if (!isNaN(value)) {
                return prev + curr
              } else {
                return prev
              }
            }, 0)
            sums[index] = sums[index].toFixed(2) + ' 元'
          } else {
            sums[index] = '0'
          }
        }
      })
      return sums
    },
    // getSummaries1(param) { // 合计
    //   console.log(param)
    //   const { columns, data } = param
    //   const sums = []
    //   columns.forEach((column, index) => {
    //     if (index === 0) {
    //       sums[index] = '合计'
    //     } else if (index === 1) {
    //       const values = data.map(item => {
    //         console.log(item, 2222)
    //         Number(parseFloat(item['收款金额']))
    //       })
    //       if (!values.every(value => isNaN(value))) {
    //         sums[index] = values.reduce((prev, curr) => {
    //           const value = Number(curr)
    //           if (!isNaN(value)) {
    //             return prev + curr
    //           } else {
    //             return prev
    //           }
    //         }, 0)
    //         sums[index] = sums[index].toFixed(2) + ' 元'
    //       } else {
    //         sums[index] = 'N/A'
    //       }
    //     }
    //   })
    // },
    searchName() { // 模糊查询姓名
      SelectMarketingManager(this.name).then(response => {
        this.dataPeople = response.data
      })
    },
    openName() {
      this.name = ''
      this.dataPeople = []
      this.dialogFormVisiblePeople = true
      this.searchName()
    },
    init() {
      this.getSelect(selectProvince, ['省份', '省份流水号'], 'Province')
      this.getSelect(searchProjectNumber, ['项目名称', '项目流水号'], 'entryName')
      this.getSelect(searchProjectNumber2, ['项目名称', '项目流水号'], 'entryName2')
      this.getSelect(PaymentPhase, ['付款阶段', '付款阶段ID'], 'PaymentPhase')
      this.getSelect(executionProgressID, ['执行进度名', '执行进度ID'], 'plannedTime')
      AccountsReceivable().then(response => {
        const data = response.data
        for (let i = 0; i < data.length; i++) {
          data[i].计划付款时间 = data[i].计划付款时间.substring(0, data[i].计划付款时间.length - 9)
          if (data[i].状态 === '1') {
            data[i].状态 = '即将拖期'
          }
          if (data[i].状态 === '2') {
            data[i].状态 = '已拖期'
          }
        }
        this.gridData = data
        this.value = response.data.length
      })
    },
    updateMoney(row, index) {
      row.edit = false
      updateMoney(row.资金明细ID, row.收款金额).then(response => {
        if (response.data[0].result !== '0') {
          this.$message.success('编辑成功')
        } else {
          this.$message.error('编辑失败')
          this.tableData2[index].收款金额 = 0
        }
      }).then(() => {
        this.getTableData()
      })
    },
    addMoney(row) {
      this.tableData2 = []
      addMoney(row.资金id).then(response => {
        if (response.data[0].result !== '0') {
          this.$message.success('收款成功')
          searchTable2(row.资金id).then(response => {
            for (let i = 0; i < response.data.length; i++) {
              this.tableData2.push({
                收款金额: response.data[i].金额,
                收款时间: response.data[i].入账时间,
                资金明细ID: response.data[i].资金明细ID,
                原收款金额: response.data[i].金额,
                edit: false
              })
            }
          })
        } else {
          this.$message.error('收款失败')
        }
      })
    },
    cancelEdit(index, row) {
      row.edit = false
      row.收款金额 = this.tableData2[index].原收款金额
      this.$message('取消修改')
    },
    deleteMoney(row) {
      this.tableData2 = []
      deleteMoney(row.资金明细ID).then(response => {
        if (response.data[0].result !== '0') {
          this.$message.success('删除成功')
          searchTable2(this.moneyID).then(response => {
            for (let i = 0; i < response.data.length; i++) {
              this.tableData2.push({
                收款金额: response.data[i].金额,
                收款时间: response.data[i].入账时间,
                资金明细ID: response.data[i].资金明细ID,
                原收款金额: response.data[i].金额,
                edit: false
              })
            }
          })
          this.getTableData()
        } else {
          this.$message.error('删除失败')
        }
      })
    },
    selectMachine(row) {
      this.projectCode = row.项目流水号
      selectMachine(this.projectCode).then(response => {
        const data = response.data
        for (let i = 0; i < data.length; i++) {
          data[i].发货日期 = data[i].发货日期.substring(0, data[i].发货日期.length - 8)
        }
        this.tableData3 = data
      })
      if (this.a === 1) {
        this.expands.push(row.项目流水号)
        this.b = row.项目流水号
        this.a = 0
      } else {
        if (this.b === row.项目流水号) {
          this.expands = []
          this.a = 1
        } else {
          this.expands = []
          this.expands.push(row.项目流水号)
          this.a = 0
          this.b = row.项目流水号
        }
      }
    },
    getRowKeys(row) {
      return row.项目流水号
    },
    getCustomerName() {
      this.customerName = ''
      this.customerNames = []
      getcustomername().then(response => {
        for (let i = 0; i < response.data.length; i++) {
          this.customerNames.push({
            value: response.data[i].客户名称,
            label: response.data[i].客户名称
          })
        }
      })
    },
    getTableData() {
      this.listLoading = true
      this.dateRange ? this.check1 = 1 : (this.check1 = 0, this.dateRange = '')
      searchTable1(this.PageCurrent, this.PageSize, this.entryNameValue, this.peopleid, this.customerName, this.check1, this.dateRange[0], this.dateRange[1], this.ordername, this.order).then(response => {
        this.listLoading = false
        const data = response.data.rows
        for (let i = 0; i < data.length; i++) {
          data[i].未支付金额 === '0' ? data[i].是否禁用 = true : data[i].是否禁用 = false
          data[i].已支付 === '0' ? data[i].是否禁用编辑 = false : data[i].是否禁用编辑 = true
          if (parseFloat(data[i].付款百分比) >= 99.9) {
            data[i].付款百分比 = 100
          }
        }
        this.tableData1 = data
        this.total = response.data.total
      })
    },
    getTableData2(row) {
      this.tableData2 = []
      this.moneyID = row.资金id
      searchTable2(this.moneyID).then(response => {
        console.log(response.data)
        for (let i = 0; i < response.data.length; i++) {
          this.tableData2.push({
            收款金额: response.data[i].金额,
            收款时间: response.data[i].入账时间,
            资金明细ID: response.data[i].资金明细ID,
            原收款金额: response.data[i].金额,
            edit: false
          })
        }
      })
    },
    handleSizeChange(val) {
      this.PageCurrent = 1
      this.PageSize = val
      this.getTableData()
    },
    handleCurrentChange(val) {
      this.PageCurrent = val
      this.getTableData()
    }
  }
}
</script>

<style scoped>

  /*.el-card {*/
  /*  !*margin-top: 15px;*!*/
  /*}*/

  .el-date-editor{
    width:237px;
  }
  .item {
    float: right;
    margin: 3px;
    margin-right: 40px;
  }
  .el-table td, .el-table th.is-leaf,
  .el-radio__inner,
  .el-input__inner{
    /*border: 1px solid black!important;*/
    width: 150px;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
  }
  /*.el-table .el-button{*/
  /*  font-size: 17px;*/
  /*}*/
</style>
<style lang="scss">
  >>>.subTableHeader {
    th {
      background: #7eaced !important;
      color: black;
    }

    tr.el-table__row td {
      background-color: #d8e5f6 !important;
    }

    tr.el-table__row.el-table__row--striped td {
      background: #e9f0f9 !important;
    }
  }
</style>
