<template>
  <div class="app-container">
    <!-- 标题按钮部分开始 -->
    <div class="tab-header webtop">
      <!-- 标题 -->
      <div>补充完善回款数据</div>
      <!-- start 添加修改按钮 -->
      <div>
        <!-- <el-button type="primary" size="small" :disabled="submitdisabled" @click="saveOrUpdate">保存</el-button> -->
        <el-button type="info" size="small" @click="handleReturn()">关闭</el-button>
      </div>
      <!-- end 添加修改按钮 -->
      <!-- end 详情按钮 -->
    </div>

    <div class="listconadd" style="padding-bottom: 100px;">
      <el-collapse value="1">
        <el-collapse-item title="1. 每日回款核对" name="1" class="formadd">
          <div class="title">
            <div>昨日销售数据</div>
            <div>
              <span style="padding-right: 20px">合计数量:{{ saleslist.length }}</span>
              <span style="padding-right: 20px">合计金额:{{ sumSalesAmount }}</span>
              <span style="padding-right: 20px">
                <el-button plain size="small" type="danger" icon="el-icon-circle-check" @click="salesListSave">保存销售记录</el-button>
              </span>
            </div>
          </div>
          <el-table show-summary :data="saleslist" border style="width: 100%">
            <el-table-column fixed label="序号" width="60px" align="center" prop="serialNumber" />
            <el-table-column label="销售日期" align="center" width="120" prop="dataDate" />
            <el-table-column label="支付渠道" align="center" width="160" prop="disbursementChannelName" />
            <el-table-column label="金额（元）" align="center" width="120" prop="amount" />
            <el-table-column label="对应公司主体" align="center" width="120" prop="companyName" />
            <el-table-column label="到账周期" align="center" width="200" prop="accountCycle" />
            <el-table-column prop="antipateCashedDate" label="日期" width="170" align="center">
              <template slot-scope="scope">
                <el-date-picker v-model="scope.row.antipateCashedDate" style="width: 140px;" type="date" placeholder="选择日期" value-format="yyyy-MM-dd" />
              </template>
            </el-table-column>
            <el-table-column label="备注" show-overflow-tooltip prop="remarks" />
          </el-table>
        </el-collapse-item>
      </el-collapse>
      <el-collapse value="2">
        <el-collapse-item title="2. 每日回款台账" name="2" class="formadd">
          <div class="title">
            <div>当日回款台账</div>
            <div>
              <span style="padding-right: 20px">合计数量:{{ incomelist.length }}</span>
              <span style="padding-right: 20px">合计金额:{{ sumIncomeAmount }}</span>
              <span style="padding-right: 20px">
                <el-button plain size="small" type="primary" icon="el-icon-plus" @click="showIncomeAdd">填写回款记录</el-button>
                <el-button plain size="small" type="danger" icon="el-icon-circle-check" @click="incomeListSave">保存回款记录</el-button>
              </span>
            </div>
          </div>
          <el-table show-summary :data="incomelist" border style="width: 100%">
            <el-table-column fixed label="序号" width="60px" align="center" prop="serialNumber" />
            <el-table-column label="回款日期" align="center" width="120" prop="dataDate" />
            <el-table-column label="回款渠道" align="center" width="140" prop="collectionChannelName" />
            <el-table-column label="回款金额（元）" align="center" width="140" prop="amount" />
            <el-table-column label="销售日期" align="center" width="120" prop="saleDate" />
            <el-table-column label="备注" show-overflow-tooltip prop="remarks" />
            <el-table-column fixed="right" width="180" label="操作" align="center">
              <template slot-scope="scope">
                <el-button type="success" size="mini" icon="el-icon-edit" @click="toEdit(scope.row)">修改</el-button>
                <el-button type="warning" size="mini" icon="el-icon-delete" @click="toDele(scope.row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-collapse-item>
      </el-collapse>
      <el-collapse value="3">
        <el-collapse-item title="3. 每日回款分析" name="3" class="formadd">
          <div class="title">
            <div>回款分析</div>
            <div>
              <span style="padding-right: 20px">合计数量:</span>
              <span style="padding-right: 20px">合计金额:</span>
              <span style="padding-right: 20px">
                <el-button plain size="small" type="success" icon="el-icon-plus" @click="checkDiff">回款分析</el-button>
                <el-button plain size="small" type="primary" icon="el-icon-plus" @click="showIncomeAdd">新增分析记录</el-button>
                <el-button plain size="small" type="danger" icon="el-icon-circle-check" @click="incomeListSave">保存回款分析</el-button>
              </span>
            </div>
          </div>
          <el-table :data="differentlist" border style="width: 100%">
            <el-table-column fixed label="序号" width="60px" align="center" prop="serialNumber" />
            <el-table-column label="销售日期" align="center" width="120" prop="saleDate" />
            <el-table-column label="支付渠道" align="center" width="120" prop="disbursementChannelName" />
            <el-table-column label="金额（元）" align="center" width="120" prop="amount" />
            <el-table-column label="对应公司主体" align="center" width="120" prop="CompanyName" />
            <el-table-column label="回款周期" align="center" width="120" prop="accountCycle" />
            <el-table-column label="应回款日期" align="center" width="120" prop="antipateCashedDate" />
            <el-table-column label="实际回款日期" align="center" width="120" prop="realCashedDate" />
            <el-table-column label="回款金额" align="center" width="100" prop="cashedAmount" />
            <el-table-column label="回款差额" align="center" width="100" prop="differentAmount" />
            <el-table-column label="备注" show-overflow-tooltip prop="remarks" />
          </el-table>
        </el-collapse-item>
      </el-collapse>
    </div>
    <el-dialog title="填写回款记录" :visible.sync="dialogVisible" width="40%" :before-close="incomeClose">
      <el-form ref="form_income" :model="incomeObj" :rules="rules" label-position="right" class="formadd">
        <div class="title">
          <div>回款信息</div>
        </div>
        <el-row>
          <el-col :span="6" class="tleftb">
            <span>回款日期</span>
          </el-col>
          <el-col :span="18" class="trightb">
            <el-form-item>{{ incomeObj.dataDate }}</el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="6" class="tleftb">
            <span>回款渠道</span>
          </el-col>
          <el-col :span="18" class="trightb">
            <el-form-item prop="collectionChannelSid"> <el-select v-model="incomeObj.collectionChannelSid" placeholder="请选择">
              <el-option v-for="item in collectionChannelList" :key="item.sid" :label="item.name" :value="item.sid" />
            </el-select></el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="6" class="tleftb">
            <span>回款金额（元）</span>
          </el-col>
          <el-col :span="18" class="trightb">
            <el-form-item prop="amount"><el-input
              v-model="incomeObj.amount"
              oninput="value=value.replace(/[^0-9.]/g,'')"
              placeholder=""
              class="addinputw"
              clearable
            /></el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="6" class="tleftb">
            <span>销售日期</span>
          </el-col>
          <el-col :span="18" class="trightb">
            <el-form-item prop="saleDate"> <el-date-picker v-model="incomeObj.saleDate" type="date" placeholder="选择日期" value-format="yyyy-MM-dd" /></el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="6" class="tleftb">
            <span>备注</span>
          </el-col>
          <el-col :span="18" class="trightb">
            <el-form-item><el-input v-model="incomeObj.remarks" type="textarea" :rows="2" placeholder="" class="addinputw" clearable /></el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="incomeClose">取 消</el-button>
        <el-button type="primary" @click="incomeListAdd()">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
  import req from '@/api/customer/csmcash'
  import {
    parseTime
  } from '@/utils/index'

  export default {
    components: {},
    data() {
      var checkIsNumberAge = (rule, value, callback) => {
        if (!value) { // 当使用时没有定义text则非空验证默认提示请输入
          callback(new Error(rule.text ? rule.text : '请输入'))
        } else {
          // const reg = /^[0-9]*$/
          const reg = /^[+-]?\d+(?:\.\d{1,4})?$/
          if (reg.test(value) && value >= 0) {
            callback()
          } else {
            if (!String(value).indexOf('.') + 1) {
              callback(new Error('请输入数字!'))
            } else {
              callback(new Error('仅支持小数点后4位!'))
            }
          }
        }
      }
      return {
        collectionChannelList: [{
            sid: '1',
            name: '微信'
          },
          {
            sid: '2',
            name: '美团'
          },
          {
            sid: '3',
            name: '京东到家'
          },
          {
            sid: '4',
            name: '归集款里的批发款'
          },
          {
            sid: '5',
            name: '饿了么'
          },
          {
            sid: '6',
            name: '支付宝'
          },
          {
            sid: '7',
            name: '京东小时购'
          }
        ],
        dialogVisible: false,
        itemIndex: 0,
        active: 0,
        inputText: '',
        submitdisabled: false,
        formobj: {
          sid: '',
          dataDate: ''
        },
        saleslist: [],
        incomelist: [],
        differentlist: [],
        incomeObj: {
          dataDate: parseTime(new Date(), '{y}-{m}-{d}'), // 回款日期
          collectionChannelSid: '1', // 回款渠道
          collectionChannelName: '', // 回款渠道
          amount: '', // 回款金额（元）
          saleDate: parseTime(new Date(), '{y}-{m}-{d}'), // 销售日期
          remarks: '', // 备注
          logsid: '',
          serialNumber: 0
        },
        incomeCurrent: null,
        rules: {
          collectionChannelSid: [{
            required: true,
            message: '请选择回款渠道',
            trigger: 'blur'
          }],
          amount: [{
            validator: checkIsNumberAge,
            trigger: 'blur'
          }],
          saleDate: [{
            required: true,
            message: '请选择销售日期',
            trigger: 'blur'
          }]
        }
      }
    },
    computed: {
      sumSalesAmount() {
        let p = 0
        this.saleslist.forEach(x => {
          p += Number(x.amount)
        })
        return Number(p).toFixed(2)
      },
      sumIncomeAmount() {
        let p = 0
        this.incomelist.forEach(x => {
          p += Number(x.amount)
        })
        return Number(p).toFixed(2)
      }
    },
    created() {},
    methods: {
      showEdit(row) {
        this.formobj.sid = row.sid
        this.formobj.dataDate = row.dataDate
        this.loadListSales()
        this.loadListIncome()
        this.loadListDifferent()
      },
      loadListSales() {
        req.listSalesByLogsid(this.formobj.sid)
          .then(resp => {
            this.saleslist = resp.data
          })
          .catch(e => {
            console.log('loadListSales -- error: ', e)
          })
      },
      loadListIncome() {
        req.listIncomeByLogsid(this.formobj.sid)
          .then(resp => {
            this.incomelist = resp.data
          })
          .catch(e => {
            console.log('loadListIncome -- error: ', e)
          })
      },
      loadListDifferent() {
        req.listDifferentByLogsid(this.formobj.sid)
          .then(resp => {
            this.differentlist = resp.data
          })
          .catch(e => {
            console.log('loadListDifferent -- error: ', e)
          })
      },
      showIncomeAdd() {
        this.dialogVisible = true
      },
      salesListSave() {
        const _this = this
        req.salesListSave(this.saleslist)
          .then(resp => {
            _this.$message({
              showClose: true,
              type: 'success',
              message: '销售数据保存成功'
            })
            _this.loadListSales()
          })
          .catch(e => {
            console.log('salesListSave -- error: ', e)
          })
      },
      incomeListSave() {
        const _this = this
        req.incomeListSave(this.incomelist)
          .then(resp => {
            _this.$message({
              showClose: true,
              type: 'success',
              message: '回款信息保存成功'
            })
            _this.loadListIncome()
          })
          .catch(e => {
            console.log('incomeListSave -- error: ', e)
          })
      },
      incomeClose() {
        this.incomeObj.dataDate = parseTime(new Date(), '{y}-{m}-{d}') // 回款日期
        this.incomeObj.collectionChannelSid = '1' // 回款渠道
        this.incomeObj.collectionChannelName = '' // 回款渠道
        this.incomeObj.amount = '' // 回款金额（元）
        this.incomeObj.saleDate = parseTime(new Date(), '{y}-{m}-{d}') // 销售日期
        this.incomeObj.remarks = '' // 备注
        this.incomeObj.logsid = ''
        this.incomeObj.serialNumber = 0
        this.$refs['form_income'].resetFields()
        this.dialogVisible = false
      },
      incomeListAdd() {
        this.$refs['form_income'].validate((valid) => {
          if (valid) {
            for (var v in this.collectionChannelList) {
              if (this.collectionChannelList[v].sid === this.incomeObj.collectionChannelSid) {
                this.incomeObj.collectionChannelName = this.collectionChannelList[v].name
                break
              }
            }

            if (this.incomeObj.serialNumber === 0) {
              const income = {
                dataDate: this.incomeObj.dataDate, // 回款日期
                collectionChannelSid: this.incomeObj.collectionChannelSid, // 回款渠道
                collectionChannelName: this.incomeObj.collectionChannelName, // 回款渠道
                amount: this.incomeObj.amount, // 回款金额（元）
                saleDate: this.incomeObj.saleDate, // 销售日期
                remarks: this.incomeObj.remarks, // 备注
                serialNumber: this.incomelist.length + 1,
                logsid: this.formobj.sid
              }
              this.incomelist.push(income)
            } else {
              const i = this.incomeObj.serialNumber - 1
              this.incomelist[i].dataDate = this.incomeObj.dataDate // 回款日期
              this.incomelist[i].collectionChannelSid = this.incomeObj.collectionChannelSid // 回款渠道
              this.incomelist[i].collectionChannelName = this.incomeObj.collectionChannelName // 回款渠道
              this.incomelist[i].amount = this.incomeObj.amount // 回款金额（元）
              this.incomelist[i].saleDate = this.incomeObj.saleDate // 销售日期
              this.incomelist[i].remarks = this.incomeObj.remarks // 备注
            }
            console.log('incomelist:  ', this.incomelist)
            this.incomeClose()
          } else {
            console.log('error submit!!')
            return false
          }
        })
      },
      toEdit(row) {
        this.incomeObj.dataDate = row.dataDate
        this.incomeObj.collectionChannelSid = row.collectionChannelSid
        this.incomeObj.collectionChannelName = row.collectionChannelName
        this.incomeObj.amount = row.amount
        this.incomeObj.saleDate = row.saleDate
        this.incomeObj.remarks = row.remarks
        this.incomeObj.logsid = row.logsid
        this.incomeObj.serialNumber = row.serialNumber

        this.dialogVisible = true
      },
      toDele(row) {
        this.incomelist = this.incomelist.filter(t => t.serialNumber !== row.serialNumber)
        for (var v in this.incomelist) {
          this.incomelist[v].serialNumber = Number(v) + 1
        }
      },
      formatNum(e) {
        e.target.value = e.target.value.replace(/[^\d.]/g, '') // 清除“数字”和“.”"-"以外的字符
        e.target.value = e.target.value.replace(/^00/, '0') // 开头不能有两个0
        if (e.target.value.indexOf('.') < 0 && e.target.value !== '' && e.target.value !== '-') {
          // 以上已经过滤，此处控制的是如果没有小数点，首位不能为类似于 01、02的金额
          console.log(e.target.value)
          e.target.value = parseFloat(e.target.value)
        }
      },
      checkDiff() {
        const _this = this
        this.$confirm('此操作将重置当日保存的回款分析记录, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
        req.incomeListSave(this.incomelist)
          .then(resp => {
            _this.$message({
              showClose: true,
              type: 'success',
              message: '回款信息保存成功'
            })
            _this.loadListIncome()
          })
          .catch(e => {
            console.log('incomeListSave -- error: ', e)
          })
          // this.$message({
          //   type: 'success',
          //   message: '删除成功!'
          // })
        }).catch(() => {
        })
      },
      handleReturn(isreload) {
        this.active = 0
        this.imgList = []
        this.imgList2 = []

        if (isreload === 'true') this.$emit('reloadlist')
        this.formobj = {
          name: '',
          codeUnified: '',
          contacts: '',
          telephone: '',
          address: '',
          bankName: '',
          bankAccount: '',
          bankAccountNumber: '',
          legalRepresentative: '',
          businessLicenseNo: '',
          businessLicenseFiles: [],
          contractInfo: {
            contractNo: '',
            contractValidity: '',
            signatory: '',
            contractPrice: '',
            handledBy: '',
            signingOrganization: '',
            contractFiles: []
          },
          codeIndex: []
        }
        this.$emit('doback')
      },
      showAdd(row) {

      },
      prev() {
        --this.active
        if (this.active < 0) {
          this.active = 0
        }
      },
      next() {
        // ++this.active;
        if (this.active++ > 3) {
          this.active = 0
        }
      },
      showDelectDialog(index) {
        this.dialogVisible = true
        this.itemIndex = index
      },
      delect() {
        this.dialogVisible = false
        // //表示先获取这个元素的下标，然后从这个下标开始计算，删除长度为1的元素
        this.formobj.codeIndex.splice(this.itemIndex, 1)
      },
      add() {
        this.formobj.codeIndex.push(
          this.inputText
        )
        this.inputText = ''
        console.log('codeIndex>>>', this.formobj.codeIndex)
      },
      submit() {
        console.log('data>>>', this.formobj)

        req.saveOrUpdate(this.formobj)
          .then(resp => {
            this.submitdisabled = false
            if (resp.success) {
              this.$message({
                showClose: true,
                type: 'success',
                message: resp.msg
              })
              this.handleReturn('true')
            } else {
              // 根据resp.code进行异常情况处理
            }
          })
      },
      backData(value) {
        console.log(value, 999)
        const aa = []
        if (value.length > 0 && value != null && value !== undefined) {
          for (var i = 0; i < value.length; i++) {
            aa.push(value[i].url)
          }
        }
        this.formobj.businessLicenseFiles = aa
      },
      backData2(value) {
        console.log(value, 999)
        const aa = []
        if (value.length > 0 && value != null && value !== undefined) {
          for (var i = 0; i < value.length; i++) {
            aa.push(value[i].url)
          }
        }
        this.formobj.contractInfo.contractFiles = aa
      }
    }
  }
</script>

<style scoped>
  .title {
    display: flex;
    flex-direction: row;
    justify-content: space-between;
    align-items: center;
  }
</style>
