<template>
  <div class="app-container">
    <!-- 搜索 -->
    <div class="filter-container">
      <el-form :inline="true" :model="searchForm">
        <el-form-item label="客户名称" >
          <el-input v-model="searchForm.client_name" placeholder="请输入客户名称" />
        </el-form-item>
        <el-form-item label="下属单位" >
          <el-input v-model="searchForm.client_company" placeholder="请输入下属单位" />
        </el-form-item>
        <el-form-item>
          <el-date-picker
            v-model="searchForm.account_date"
            type="month"
            placeholder="选择月"
            :picker-options="pickerOptions"
            value-format="yyyy-MM">
          </el-date-picker>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" @click="fetchData">搜索</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-download" @click="handleDownload">导出</el-button>
        </el-form-item>
      </el-form>
    </div>
    <!-- 表格 -->
    <div class="mb-10 f700">客户总数：{{total}}</div>
    <el-table v-loading="listLoading" 
      :data="firmList" border fit 
      :span-method="objectSpanMethod" 
      highlight-current-row :height="clientHeight-184"
      style="width: 100%;">
      <!-- <el-table-column label="ID" prop="client_id" align="center" width="80" fixed="left"></el-table-column> -->
      <el-table-column label="客户编号" prop="client_num" align="center" fixed="left"></el-table-column>
      <el-table-column label="客户名称" prop="client_name" align="center" fixed="left"></el-table-column>
      <el-table-column label="下属单位" prop="client_company" align="center" fixed="left"></el-table-column>
      <!-- 有公共部分开始 -->
      <el-table-column label="类型" prop="product_type" align="center">
        <template slot-scope="scope">{{getProductType(scope.row.product_type)}}</template>
      </el-table-column>
      <el-table-column label="品种" prop="variety_num" align="center"></el-table-column>
      <el-table-column label="出厂数量(吨)" prop="over_ton" align="center"></el-table-column>
     
      <el-table-column label="销售单价(元)" prop="sale_fee" align="center"></el-table-column>
      <el-table-column label="销售总额(元)" prop="sale_sum" align="center"></el-table-column>
       <el-table-column label="成本单价(元)" prop="base_fee" align="center"></el-table-column>
      <el-table-column label="成本总额(元)" prop="base_sum" align="center"></el-table-column>
      <el-table-column label="运费(元)" prop="post_fee" align="center"></el-table-column>
      <el-table-column label="返点(元)" prop="return_fee" align="center"></el-table-column>
      <el-table-column label="净利润" prop="profit_fee" align="center"></el-table-column>
      <!-- 有公共部分结束 -->
      <el-table-column label="应收" prop="should_fee" align="center"></el-table-column>
      <el-table-column label="当月回款" prop="this_month_fee_sum" align="center"></el-table-column>
      <el-table-column label="当月欠款" prop="this_month_fee_owe" align="center"></el-table-column>
      <el-table-column label="上月欠款" prop="last_month_fee_owe" align="center"></el-table-column>
      <el-table-column label="总欠款" prop="all_fee_owe" align="center"></el-table-column>
      <el-table-column label="预收款" prop="init_pay_sum" align="center"></el-table-column>
      <el-table-column label="当月开票金额" prop="this_month_sell_fee" align="center"></el-table-column>
      <!-- <el-table-column label="当月回款" prop="add_month_fee" align="center"></el-table-column>
      <el-table-column label="当月欠款" prop="owe_month_fee" align="center"></el-table-column>
      <el-table-column label="上月欠款" prop="last_month_owe" align="center"></el-table-column>
      <el-table-column label="总欠款" prop="owe_sum" align="center"></el-table-column>
      <el-table-column label="预收款" prop="init_pay" align="center"></el-table-column>
      <el-table-column label="当月开票金额" prop="sell_fee" align="center"></el-table-column> -->
      <el-table-column label="备注" prop="account_note" align="center"></el-table-column>
      <el-table-column label="操作" align="center" width="120" fixed="right">
        <template slot-scope="scope" v-if="scope.row.client_id">
          <el-dropdown>
            <el-button type="primary" size="mini">
              管理<i class="el-icon-arrow-down el-icon--right"></i>
            </el-button>
            <el-dropdown-menu slot="dropdown" style="text-align:center;">
              <el-dropdown-item>
                <el-button size="mini" @click="goDetail(scope.row.client_id)"> 收款明细 </el-button>
              </el-dropdown-item>
              <!-- <el-dropdown-item>
                <el-button size="mini" @click="handleEntry(scope.row.client_id)"> 预 收 款 </el-button>
              </el-dropdown-item> -->
              <el-dropdown-item>
                <el-button size="mini" @click="handleNote(scope.row.client_id)"> 查看备注 </el-button>
              </el-dropdown-item>
              <el-dropdown-item>
                <el-button size="mini" @click="goTic(scope.row.client_id)"> 开票记录 </el-button>
              </el-dropdown-item>
              <el-dropdown-item>
                <el-button size="mini" @click="getReceipt(scope.row.client_id, scope.row.client_company)"> 磅单回执 </el-button>
              </el-dropdown-item>
               <el-dropdown-item>
                <el-button size="mini" @click="goRefund(scope.row.client_id)"> 退款明细 </el-button>
              </el-dropdown-item>
              <el-dropdown-item>
                <el-button size="mini" @click="getRefund(scope.row.client_id)"> 退款 </el-button>
              </el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </template>
      </el-table-column>     
    </el-table>
    <!-- 翻页 -->
    <!-- <pagination v-show="total>0" 
      :total="total" 
      :page.sync="searchForm.page" 
      :page_len.sync="searchForm.page_len"
      :limit.sync="searchForm.limit" 
      @pagination="fetchData" /> -->
    <!-- 预收款信息 -->
    <el-dialog title="预收款信息" :visible.sync="dialogEntry" center width="400px" @close="closeDialog">
      <el-form :model="entryInfo" label-width="70px" :rules="formRules" ref="postForm" >
        <el-form-item label="金额：" prop="order_fee">
          <el-input v-model="entryInfo.order_fee" placeholder="请输入金额"/>
        </el-form-item>
        <el-form-item label="备注：" prop="order_note">
          <!-- <el-input v-model="entryInfo.order_note" placeholder="请输入备注" maxlength=20 /> -->
          <el-input
            type="textarea"
            :rows="3"
            placeholder="请输入备注"
            maxlength=20
            v-model="entryInfo.order_note">
          </el-input>
          <div class="price_name">{{entryInfo.order_note.length}}/20</div>
        </el-form-item>
      </el-form>
      <el-button style="margin-left:140px" type="primary" @click="submitForm">保存</el-button>
    </el-dialog>
    <!-- 备注弹窗 -->
    <el-dialog title="备注" :visible.sync="dialogNote" center width="540px">
      <el-form :model="entryInfo" label-width="70px">
        <el-form-item label="备注：">
          <el-input
            type="textarea"
            :rows="4"
            placeholder="请输入内容"
            v-model="noteContent">
          </el-input>
        </el-form-item>
      </el-form>
      <el-button style="margin-left:200px" type="primary" @click="submitNote">修改</el-button>
    </el-dialog>
    <!-- 退款弹窗 -->
    <el-dialog title="退款" :visible.sync="dialogRefund" center width="540px" @close="closeDialog">
      <el-form :model="refundInfo" label-width="100px" :rules="formRulesRefund" ref="postForm" >
        <el-form-item label="退款金额：" prop="order_fee">
          <el-input placeholder="请输入退款金额" v-model="refundInfo.order_fee"></el-input>
        </el-form-item>
        <el-form-item label="备注：">
          <el-input
            type="textarea"
            :rows="4"
            placeholder="请输入内容"
            v-model="refundInfo.order_note">
          </el-input>
        </el-form-item>
      </el-form>
      <el-button style="margin-left:200px" type="primary" @click="submitRefund">保存</el-button>
    </el-dialog>
    <!-- 进度条 -->
    <el-progress v-show="showprogress" class="progress" :percentage="percentage"></el-progress>
  </div>
</template>


<script>
import { 
  listClientAccount, 
  saveClientAccount, 
  detailNote, 
  saveNote, 
  exportClient, 
  exportPic, 
  saveClientRefund 
} from '@/api/order/index'
import { checkRqInput, checkNum0, checkNum1 } from '@/utils/validate'
import { baseUrl } from '@/utils/env.js'
import axios from 'axios'
import JSZip from 'jszip'
import FileSaver from 'file-saver'

const getFile = url => {
  return new Promise((resolve, reject) => {
    axios({
        method:'get',
        url,
        responseType: 'arraybuffer'
    }).then(data => {
        resolve(data.data)
    }).catch(error => {
        reject(error.toString())
    })
  })
}

export default {
  data() {
    return {
      firmList: [],  // 列表
      total: 0,  // 总数
      listLoading: true,
      dialogEntry:false, // 预收款弹窗状态
      entryInfo: {
        order_fee: '',
        order_note: ''
      }, // 预收款输入信息
      refundInfo: {
        order_fee: '',
        order_note: ''
      },  // 退款输入信息
      dialogNote: false, // 备注弹窗
      dialogRefund: false, // 退款弹窗
      noteContent: '', // 备注内容
      // 校验规则
      formRules: {
        order_fee: [ checkRqInput, checkNum0 ],
        order_note: [ checkRqInput ],
      },
      // 退款校验
      formRulesRefund: {
        order_fee: [ checkRqInput, checkNum1 ],
        order_note: [ checkRqInput ],
      },
      // 搜索相关数据
      searchForm: {
        page: 1,
        page_len: 100000000,
        enterprise_id:1
      },
      baseUrl,
      percentage: 0, // 进度条数据
      dataLength: 0, // 数据条数
      showprogress: false, // 进度条状态
      clientHeight: 0, // 屏幕的高度
      pickerOptions: this.banTime(), 
    }
  },
  created() {
    this.fetchData()
    this.clientHeight = `${document.documentElement.clientHeight}`;
  },
  methods: {
    // 限制月份
    banTime() {
      return {
        disabledDate(time) {
          const date = new Date()
          const year = date.getFullYear()
          let month = date.getMonth() + 1
          if (month >= 1 && month <= 9) {
            month = '0' + month
          }
          const currentdate = year.toString() + month.toString()
          const timeyear = time.getFullYear()
          let timemonth = time.getMonth() + 1
          if (timemonth >= 1 && timemonth <= 9) {
            timemonth = '0' + timemonth
          }
          const timedate = timeyear.toString() + timemonth.toString()
          return currentdate < timedate
        }
      }
    },
    // 获取列表
    fetchData(obj={}) {
      if(obj.page) {
        this.searchForm.page = obj.page
        this.searchForm.page_len = obj.page_len
      }
      this.listLoading = true
      this.firmList = []
      this.$http(listClientAccount(this.searchForm), (res) => {
        let firmList = res.data.result
        // console.log(firmList)
        // 把合并项整理分开
        firmList.map((val, index) => {
          // if(val.group.length==1) {
          //   let groupObj = Object.assign({}, val, {})
          //   delete groupObj.group
          //   groupObj.groupFlag = true  // 记录是否在此项开始
          //   groupObj.groupSum = 0
          //   for(let sum = 0; sum<val.group.length; sum++) {
          //     if(val.group[sum].data_list==0) {
          //       groupObj.groupSum+=1
          //     }
          //     else {
          //       groupObj.groupSum+=val.group[sum].data_list.length
          //     }
          //   }
          //   if(val.group[0].data_list.length==0) {
          //     let obj = Object.assign({}, val.group[0], {})
          //     delete obj.data_list
          //     obj.flag = true  // 记录是否在此项开始
          //     obj.sum = 1  // 一共多少项相同项(默认一项)
          //     this.firmList.push(obj)
          //   } else {
          //     for(let i=0;val.data_list.length>i;i++) {
          //       let obj = Object.assign({}, val.group[0], {})
          //       if(i==0) {
          //         obj.groupFlag = true  // 记录是否在此项开始
          //         obj.groupSum = groupObj.groupSum
          //         obj.client_name = groupObj.client_name
          //         obj.flag = true // 记录是否在此项开始
          //         obj.sum = obj.data_list.length // 一共多少项相同项
          //       }
          //       delete obj.data_list
          //       for(let item in val.data_list[i]) {
          //         obj[item] = val.data_list[i][item];
          //       }
          //       this.firmList.push(obj)
          //     }
          //   }
          // } else {
            for(let i=0;val.group.length>i;i++) {  // 在客户名称下有几个客户单位
              console.log()
              let groupObj = Object.assign({}, val, {})  // 
              // console.log(obj, 'obj', i)
              if(i==0) {
                groupObj.groupFlag = true // 记录是否在此项开始
                groupObj.groupSum = 0
                for(let sum = 0; sum<groupObj.group.length; sum++) {
                  if(groupObj.group[sum].data_list==0)  groupObj.groupSum+=1
                  else groupObj.groupSum+=groupObj.group[sum].data_list.length
                }
              }
              delete groupObj.group
              for(let item in val.group[i]) { 
                groupObj[item] = val.group[i][item]; // 分解首个需要合并项
              }
              if(groupObj.data_list.length==0) {
                let obj = Object.assign({}, groupObj, {})
                delete obj.data_list
                obj.flag = true  // 记录是否在此项开始
                obj.sum = 1  // 一共多少项相同项(默认一项)
                this.firmList.push(obj)
              } else {
                for(let index=0;groupObj.data_list.length>index;index++) {
                  let obj = Object.assign({}, groupObj, {})
                  if(index==0) {
                    obj.flag = true // 记录是否在此项开始
                    obj.sum = obj.data_list.length // 一共多少项相同项
                  } else {
                    obj.groupFlag = false
                    obj.groupSum = 0
                  }
                  delete obj.data_list
                  for(let item1 in groupObj.data_list[index]) {
                    obj[item1] = groupObj.data_list[index][item1];
                  }
                  this.firmList.push(obj)
                }
              }
            }
          // }
        })
        // 整理合计选项
        let sum = {
          groupSum:1,
          groupFlag: true,
          flag: true, // 记录是否在此项开始
          sum: 1, // 一共多少项相同项
          client_id: '',
          client_num: "合计",
          client_company: '',
          over_ton: res.data.G_count,
          sale_sum: res.data.G_sell_sum,
          base_sum: res.data.G_base_sum,
          post_fee: res.data.G_post,
          return_fee: res.data.G_return,
          profit_fee: res.data.G_profit,
          should_fee: res.data.G_should,
          add_month_fee: res.data.G_month_fee,
          owe_month_fee: res.data.G_month_own,
          last_month_owe: res.data.G_last_mont_own,
          owe_sum: res.data.G_own_sum,
          init_pay: res.data.G_init_pay,
          sell_fee: res.data.G_sell_fee,
        }
        this.firmList[this.firmList.length] = sum
        this.total = res.data.data_sum
        this.listLoading = false
        console.log(this.firmList)
      })
    },
    // 整合同项
    objectSpanMethod({ row, column, rowIndex, columnIndex }) {
      if (columnIndex==0||columnIndex==2||columnIndex==13||columnIndex==20||columnIndex==21) {
        if (row.flag) {
          return {
            rowspan: row.sum,  // 由row.falg标志开始一共几项合并为一项
            colspan: 1
          };
        } else {
          return {
            rowspan: 0,
            colspan: 0
          };
        }
      }
      if(columnIndex==1||columnIndex==14||columnIndex==15||columnIndex==16||columnIndex==17||columnIndex==18||columnIndex==19) {
        // console.log(row.groupSum, 'row')
        if (row.groupFlag) {
          return {
            rowspan: row.groupSum,  // 由row.groupFalg标志开始一共几项合并为一项
            colspan: 1
          };
        } else {
          return {
            rowspan: 0,
            colspan: 0
          };
        }
      }
    },
    // 配送产品
    getProductType(value) {
      return value=="type-00"?"散装":(value=="type-01"?"袋装":"")
    },
    // 导出
    handleDownload() {
      this.$http(exportClient(this.searchForm), (res) => {
        window.location.href = this.baseUrl + res.data.url
      })
    },
    // 收款明细
    goDetail(client_id) {
      this.$router.push({ path: '/financialManagement/client/payDetail',query:{client_id: client_id}})
    },
    // 退款明细
    goRefund(client_id) {
      this.$router.push({ path: '/financialManagement/client/refundDetail',query:{client_id: client_id}})
    },
    // 结算运费
    handleEntry(client_id) {
      this.entryInfo.client_id = client_id
      this.dialogEntry = true
    },
    // 保存结算运费
    submitForm() {
      this.$refs['postForm'].validate((valid) => {
        if (valid) {
          this.$http(saveClientAccount(this.entryInfo), res => {
            this.$message({
              message: '成功',
              type: 'success'
            })
            this.fetchData()
            this.dialogEntry = false
          })
        } else {
          return false
        }
      })
    },
    // 查看备注
    handleNote(client_id) {
      this.$http(detailNote(client_id), res => {
        this.$message({
          message: '成功',
          type: 'success'
        })
        this.noteContent = res.data.account_note
        this.clientId = client_id
        this.dialogNote = true
      })
    },
    // 修改备注
    submitNote() {
      let json = {
        client_id: this.clientId,
        account_note: this.noteContent
      }
      this.$http(saveNote(json), res => {
        this.$message({
          message: '成功',
          type: 'success'
        })
        this.fetchData()
        this.dialogNote = false
      })
    },
    // 开票记录
    goTic(client_id) {
      this.$router.push({ path: '/financialManagement/client/ticManagement',query:{client_id: client_id}})
    },
    // 磅单回执
    getReceipt(client_id, client_company) {
      this.$confirm('下载', `确认下载回执？`, () => {
        this.$http(exportPic(client_id), (res) => {
          let imgList = res.data
          if(imgList.length <= 0) {
            this.$message({
              message: '没有回执',
              type: 'warning'
            })
            return ''
          }
          let dataLength = imgList.length
          dataLength > 0 ? this.showprogress = true : this.showprogress = false
          const data = imgList// 需要下载打包的路径, 可以是本地相对路径, 也可以是跨域的全路径
          const zip = new JSZip()
          const cache = {}
          const promises = []
          let num = 0
          data.forEach(item => {
            let url = this.baseUrl+item.pic_path
            const promise = getFile(url).then(data => { // 下载文件, 并存成ArrayBuffer对象
              const arr_name = item.pic_path.split(".")
              const file_name = item.pic_name + '.' + arr_name[arr_name.length - 1] // 获取文件名
              zip.file(file_name, data, { binary: true }) // 逐个添加文件
              cache[file_name] = data
              num++
              this.percentage = (num/dataLength*100).toFixed(2)-1
            })
            promises.push(promise)
          })
          Promise.all(promises).then(() => {
            zip.generateAsync({type:"blob"}).then(content => { // 生成二进制流
              let myDate = new Date();
              let mytime = ''+myDate.getFullYear()+(myDate.getMonth()+1)+myDate.getDate(); 
              FileSaver.saveAs(content, client_company+'-'+mytime+".zip") // 利用file-saver保存文件
              this.percentage = 100
              setTimeout(()=> {
                this.showprogress = false
                this.percentage = 0
              }, 1000)
            })
          })
          // imgList.map((val, index) => {
          //   let url = this.baseUrl+val.pic_path
          //   let name = val.pic_name
          //   // this.downloadByBlob(url, name)
          // })
        })
      })
      
    },
    // 退款
    getRefund(client_id) {
      // saveClientRefund
      this.clientId = client_id
      this.dialogRefund = true
    },
    submitRefund() {
      let json = this.refundInfo
      json.client_id = this.clientId
      this.$http(saveClientRefund(json), res => {
        this.$message({
          message: '成功',
          type: 'success'
        })
        this.fetchData()
        this.dialogRefund = false
      })
    },
    // // 
    // downloadByBlob(url,name) {
    //   let image = new Image()
    //   image.setAttribute('crossOrigin', 'anonymous')
    //   image.src = url
    //   image.onload = () => {
    //     let canvas = document.createElement('canvas')
    //     canvas.width = image.width
    //     canvas.height = image.height
    //     let ctx = canvas.getContext('2d')
    //     ctx.drawImage(image, 0, 0, image.width, image.height)
    //     canvas.toBlob((blob) => {
    //       let url = URL.createObjectURL(blob)
    //       this.download(url,name)
    //       // 用完释放URL对象
    //       URL.revokeObjectURL(url)
    //     })
    //   }
    // },
    // // 
    // download(href, name) {
    //   let eleLink = document.createElement('a')
    //   eleLink.download = name
    //   eleLink.href = href
    //   eleLink.click()
    //   eleLink.remove()
    // },
    // 关闭弹窗
    closeDialog() {
      this.$refs['postForm'].resetFields();
    },
  }
}
</script>

<style lang='scss' scoped>
  .box {
    width: 496px;
    padding: 20px;
    text-indent:2em;
    border: 1px solid #ccc;
  }
  .progress {
    position: fixed;
    right: 20px;
    bottom: 10px;
    width: 80%;
    z-index: 99;
  }
  .price_name {
    position: absolute;
    right: 10px;
    top: 40px;
  }
</style>