<template>
  <div class="app-container">
    <div class="filter-container">
      <el-button size="mini" type="primary" @click="combinedQuery = !combinedQuery">组合查询</el-button>
      <el-button :size="sizeType" type="green" @click="exportBtn">导出</el-button>
      <el-button v-if="permissionFlag1" :size="sizeType" type="danger"  @click="deleteCharge()">批量冲销</el-button>
      <el-button :size="sizeType" type="warning" @click="printData()">批量打印</el-button>
      <el-card class="box-card" v-if="combinedQuery">
      <el-input :size="sizeType" v-model="search.clientName" placeholder="客户名称" style="width: 200px;" class="filter-item"/>
        <el-button @click="selectCustomersBtn" :size="sizeType" type="primary" plain>多个客户查询</el-button>
        <el-input :size="sizeType" v-model="search.orderCode" placeholder="订单编号" style="width: 120px;" class="filter-item"/>
        <el-input :size="sizeType" v-model="search.chargeCode" placeholder="收款编号" style="width: 120px;" class="filter-item"/>
        <el-input :size="sizeType" v-model="search.accountName" placeholder="会计科目" style="width: 150px;" class="filter-item"/>
        <el-input :size="sizeType" v-model="search.receiveCode" placeholder="收据号" style="width: 120px;" class="filter-item"/>
        <el-input :size="sizeType" v-model="search.voucherCode" placeholder="凭证号" style="width: 150px;" class="filter-item"/>
        <el-input :size="sizeType" v-model="search.payMan" placeholder="交款人" style="width: 100px;" class="filter-item"/>
        <el-input :size="sizeType" v-model="search.chargeMan" placeholder="收款人" style="width: 100px;" class="filter-item"/>
        <el-input :size="sizeType" v-model="search.platformOrderID" placeholder="平台单号" style="width: 120px;" class="filter-item"/>
<!--      <el-select :size="sizeType" v-model="search.dataKind">-->
<!--        <el-option-->
<!--          v-for="item in stateOptions"-->
<!--          :key="item.value"-->
<!--          :label="item.label"-->
<!--          :value="item.value"></el-option>-->
<!--      </el-select>-->
        <el-select size="mini" v-model="search.voidFlag" placeholder="单据状态" class="filter-item">
          <el-option label="全部" :value="-1"></el-option>
          <el-option label="正常" :value="0"></el-option>
          <el-option label="冲销" :value="1"></el-option>
        </el-select>
      <el-date-picker
        style="width: 225px"
        :size="sizeType"
        v-model="searchTime"
        type="daterange"
        range-separator="-"
        start-placeholder="开始日期"
        end-placeholder="结束日期"
        format="yyyy-MM-dd"
        value-format="yyyy-MM-dd"
        :default-time="['00:00:00', '23:59:59']">
      </el-date-picker>
      <el-button :size="sizeType" type="primary" icon="el-icon-search" @click="searchData">
        搜索
      </el-button>
      <el-button :size="sizeType"  type="danger" @click="resetForm">
        重置
      </el-button>
      </el-card>

      <div class="top-right-btn">
<!--        <el-switch-->
<!--          size="mini"-->
<!--          class="filter-item"-->
<!--          v-model="search.voidFlag"-->
<!--          style="margin-right: 1em"-->
<!--          inactive-color="#13ce66"-->
<!--          active-text="已删除"-->
<!--          inactive-text="未删除"-->
<!--          :active-value="1"-->
<!--          :inactive-value="0"-->
<!--          @change="getList"-->
<!--        >-->
<!--        </el-switch>-->
        <el-tooltip class="item" effect="dark" content="刷新" placement="top">
          <el-button size="mini" circle icon="el-icon-refresh" @click="getList"/>
        </el-tooltip>
      </div>
    </div>
    <el-table
      :size="sizeType"
      :data="tableData"
      v-loading="listLoading"
      row-key="id"
      border
      style="margin-top: 10px"
      ref="orderTable"
      show-summary
      max-height="600"
      :summary-method="getSummaries"
      @row-click="handleClickTableRow"
      @selection-change="handleSelectionChange"
      default-expand-all>
      <el-table-column
        type="selection"
        fixed="left"
        width="55">
      </el-table-column>
      <el-table-column
        label="序号"
        fixed
        align="center"
        width="50"
        type="index">
        <template slot-scope="scope">
          <span>{{(listData.page - 1) *listData.pageSize + scope.$index + 1}}</span>
        </template>
      </el-table-column>

<!--      <el-table-column-->
<!--        fixed-->
<!--        label="操作">-->
<!--        <template slot-scope="{row}">-->
<!--            <el-button-->
<!--              title="查看订单"-->
<!--              @click.stop="openDetail(row)"-->
<!--              type="primary"-->
<!--              icon="el-icon-view"-->
<!--              :size="sizeType">-->
<!--            </el-button>-->
<!--        </template>-->
<!--      </el-table-column>-->
      <el-table-column
        prop="chargeCode"
        label="收款编号"
        width="92">
      </el-table-column>
<!--      <el-table-column-->
<!--        prop="financeCode"-->
<!--        label="锁定标记">-->
<!--        <template slot-scope="{row}">-->
<!--          <el-tag v-if="row.lockFlag == 1" type="danger">锁定</el-tag>-->
<!--          <el-tag v-else type="success">未锁定</el-tag>-->
<!--        </template>-->
<!--      </el-table-column>-->
      <el-table-column
        prop="orderCode"
        width="95"
        label="订单编号">
        <template slot-scope="{row}">
          <a href="javascript:;" style="color: #20a0ff" @click.stop="getOrderStep(row)">{{row.orderCode}}</a>
        </template>
      </el-table-column>
      <el-table-column
        prop="clientName"
        show-overflow-tooltip
        label="客户名称"></el-table-column>
      <el-table-column
        prop="orderPlatformOrderID"
        show-overflow-tooltip
        label="平台单号"></el-table-column>

      <el-table-column
        prop="orderName"
        show-overflow-tooltip
        label="印品名称">
        <template slot-scope="{row}">
          <a  href="javascript:;" style="color: #20a0ff" @click="openDetail(row.idOrder)" class="ellipsis"> {{ row.orderName }}</a>
        </template>
      </el-table-column>
      <el-table-column
        prop="receiveCode"
        width="110"
        show-overflow-tooltip
        label="收据号"></el-table-column>
      <el-table-column
        prop="receivableMoney"
        width="130"
        label="收款金额">
        <template slot-scope="{row}">
          <span style="color: #e4493c"  v-if="row.receivableMoney && row.voidFlag==1">{{row.receivableMoney | formatMoney}}</span>
          <span v-else="row.receivableMoney && row.voidFlag==0">{{row.receivableMoney | formatMoney}}</span>
        </template>
      </el-table-column>
      <el-table-column
        prop="agioMoney"
        label="折扣金额"></el-table-column>
      <el-table-column
        prop="agioMemo"
        label="折扣备注"></el-table-column>

      <el-table-column
        prop="accountName"
        show-overflow-tooltip
        label="会计科目"></el-table-column>
      <el-table-column
        prop="voucherCode"
        label="凭证号"
      width="120">
        <template slot-scope="{row}">
          <el-tooltip :content="row.voucherCode" placement="top-start" effect="light">
            <span v-if="row.voucherCode">{{plusXing(row.voucherCode,6,4)}}</span>
          </el-tooltip>
        </template>
      </el-table-column>
      <el-table-column
        prop="payMan"
        label="交款人"></el-table-column>
      <el-table-column
        prop="chargeMan"
        label="收款人"></el-table-column>
      <el-table-column
        label="单据状态"
        prop="voidFlag"
      >
        <template slot-scope="{row}">
          <el-tag v-if="row.voidFlag == 0" type="success" size="mini">正常</el-tag>
          <el-tag v-else-if="row.voidFlag == 1" size="mini" type="danger">冲销</el-tag>
        </template>
      </el-table-column>
      <el-table-column
        prop="chargeKind"
        label="收款类型">
        <template slot-scope="{row}">
          <el-tag v-if="row.chargeKind == 0" size="mini">现金/转账</el-tag>
          <el-tag v-else-if="row.chargeKind == 1" size="mini" type="success">物流代收</el-tag>
          <el-tag v-else-if="row.chargeKind == 2" size="mini" type="warning">预存冲抵</el-tag>
          <el-tag v-else-if="row.chargeKind == 3" size="mini" type="primary">其他收款单收款</el-tag>
<!--          <el-tag v-else-if="row.chargeKind == 4" size="mini" type="danger">物流代收</el-tag>-->
          <el-tag v-else-if="row.chargeKind == 5" size="mini" type="danger">银联</el-tag>
          <el-tag v-else-if="row.chargeKind == 6" size="mini" type="danger">支付宝</el-tag>
          <el-tag v-else-if="row.chargeKind == 7" size="mini" type="danger">微信</el-tag>
        </template>
      </el-table-column>
      <el-table-column
      prop="chargeDate"
      label="收款时间"
      width="120">
      <template slot-scope="{row}">
        <span v-if="row.chargeDate">{{ row.chargeDate | getTime }}</span>
      </template>
      </el-table-column>
        <el-table-column
          prop="orderCreateTime"
          label="订单制单时间"
          width="120">
          <template slot-scope="{row}">
            <span v-if="row.orderCreateTime">{{ row.orderCreateTime | getTime }}</span>
          </template>
    </el-table-column>
      <el-table-column label="备注" prop="chargeMemo" show-overflow-tooltip></el-table-column>
    </el-table>
    <pagination v-show="listData.total>0" :total="listData.total" :page.sync="listData.page" :limit.sync="listData.pageSize" @pagination="getList"/>
    <el-dialog title="订单详情" :visible.sync="detailVisible" class="orderDetailDialog" width="1200px" top="10px">
      <order-detail ref="orderDetail"></order-detail>
    </el-dialog>
    <cancledialog @tableRefresh="tableRefresh" ref="confirmDialog" :noDoubleClick="true"></cancledialog>
    <order-step ref="orderStep"></order-step>
    <el-dialog title="删除记录" :visible.sync="voidVisible" width="500px">
      <div style="margin-bottom: 10px;margin-left: 5px;font-size: 12px" v-html="deleteHtml"></div>
      <el-form label-width="80px" label-position="right">
        <el-form-item label="删除说明">
          <el-input type="textarea" v-model="deleteMemo"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="voidVisible = false">取 消</el-button>
        <el-button type="primary" :disabled="deleteLoader" @click="deleteBtn">确 定</el-button>
      </div>
    </el-dialog>
    <el-dialog title="选择客户" top="30" width="800px" :visible.sync="dialogTableVisible">
      <el-input :size="sizeType" v-model="searchTable.keyWord" placeholder="关键字" style="width: 200px;" class="filter-item" @keyup.enter.native="getClientInfoList"/>
      <el-button :size="sizeType" type="primary" icon="el-icon-search" @click="getClientInfoList">
        搜索客户
      </el-button>
      <el-button type="primary" :size="sizeType" icon="el-icon-refresh" @click="clientRefresh">刷新</el-button>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-table
            style="margin-top: 10px"
            ref="multipleTable"
            @row-click="handleClickClientRow"
            border
            size="mini"
            row-key="id"
            @selection-change="handleClientChange"
            :data="gridData">
            <el-table-column
              align="center"
              type="selection"
              :reserve-selection="true"
              width="55">
            </el-table-column>
            <el-table-column
              align="center"
              width="100px"
              prop="clientCode"
              label="客户编号">
            </el-table-column>
            <el-table-column
              width="150px"
              prop="clientName"
              show-overflow-tooltip
              label="客户名称">
              <template slot-scope="{row}">
                <span class="ellipsis"> {{ row.clientName }}</span>
              </template>
            </el-table-column>
          </el-table>
        </el-col>
        <el-col :span="12">
          <div v-if="checkClientList.length>0" style="border: 1px solid #ddd;padding: 7px;padding-top: 7px;margin-bottom: 10px;">
            <el-tag
              :key="tag.id"
              size="mini"
              style="margin-top: 5px"
              v-for="tag in checkClientList"
              closable
              :disable-transitions="false"
              @close="handleCloseClient(tag.id)">
              {{tag.clientName}}
            </el-tag>
          </div>
          <div v-if="checkClientList.length>0" style="display: block;width: 100%;margin-bottom: 10px"> <el-button :size="sizeType" type="success" icon="el-icon-search" @click="searchData">
            搜索单据
          </el-button></div>
        </el-col>
      </el-row>

      <pagination
        v-show="listData2.total>0"
        :total="listData2.total"
        :page.sync="listData2.page"
        :limit.sync="listData2.pageSize"
        @pagination="getClientInfoList"/>
    </el-dialog>
  </div>
</template>

<script>
import OrderDetail from '@/components/orderDetail/orderDetail'
import {deleteChargeData, getChargeDataList} from '@/api/orderCharge/collectionRecords'
import Cancledialog from '@/components/Dialog/Cancledialog.vue'
import axios from "axios";
import {changeMoneyToChinese, doLocalPrint} from '@/utils/index'
import OrderStep from "@/components/orderStep/orderStep";
import {exportData} from "@/api/orderCharge/orderCollection";
import {formatMoney} from '@/filters/index'
import {ifPermission} from "@/api/order/orderList";
import {getInfo} from "@/api/doc/client/client";
const  searchForm = {
  clientName: '',
  financeCode: '',
  chargeCode: '',
  orderCode: '',
  accountName: '',
  voucherCode: '',
  chargeMan: '',
  platformOrderID: '',
  dataKind: '',
  beginTime: '',
  endTime: '',
  receiveCode: '',
  payMan: '',
  voidFlag: 0,
  idClients:""
}
export default {
  name: 'collectionRecords',
  components: {
    OrderStep,
    OrderDetail,Cancledialog
  },
  data() {
    return {
      gridData:[],
      dialogTableVisible:false,
      checkClientList:[],
      combinedQuery: false,
      permissionFlag1: false,
      voidVisible: false,
      deleteLoader: false,
      sizeType: 'mini',
      detailVisible: false,
      search: Object.assign({}, searchForm),
      chosenList: [],
      deleteMemo:'',
      deleteHtml:'',
      tableData: [],
      collection: {},

      listLoading: false,
      listData: {
        total: 0,
        page: 1,
        pageSize: 20
      },
      listData2: {
        total: 0,
        page: 1,
        pageSize: 20
      },
      searchTime: [],
      searchTable:{
        keyWord:""
      },

      stateOptions: [
        {
          label: '订单定金',
          value: 0
        },
        {
          label: '订单收款',
          value: 1
        },
      ],
    }
  },
  created() {
    this.getList()
  },
  mounted() {
    this.checkPermission('PlDel:admin')
    this.getClientInfoList();
  },
  methods: {
    clientRefresh(){
      this.listData2.page = 1;
      this.searchTable.keyWord = "";
      this.checkClientList = [];
      this.getClientInfoList();
    },
    handleClickClientRow(row, event, column) {
      const _that = this;
      _that.$nextTick(() => {
        _that.$refs.multipleTable.toggleRowSelection(row);
      })
    },
    handleClientChange(val){
      var _that = this;
      _that.checkClientList = val;
    },
    getClientInfoList(){
      var _that = this;
      var params = _that.searchTable
      var page = {
        pageIndex: _that.listData2.page,
        pageSize: _that.listData2.pageSize
      }
      if (_that.searchTable.keyWord) {
        var data = {
          'params': JSON.stringify(params),
          'page': JSON.stringify(page)
        }
      } else {
        var data = {
          'params': {},
          'page': JSON.stringify(page)
        }
      }

      // console.log(data);
      getInfo(data).then(response => {
        // console.log("tableData",response)
        const data = response.data
        // //  组合表单数据
        _that.gridData = data
        _that.listData2.total = response.total
        // console.log(_that.tableData)
      }).catch(err => {
      })
    },
    selectCustomersBtn(){
      var _that = this;
      _that.dialogTableVisible = true;
      _that.listData2.page = 1;
      _that.searchTable.keyWord = "";
      _that.checkClientList = [];
      _that.$nextTick(() => {
        _that.$refs.multipleTable.clearSelection();
      })

    },
    handleCloseClient(id) {
      console.log(id);
      var _that = this;
      _that.checkClientList.splice(this.checkClientList.indexOf(id), 1);
      for (let i = 0; i < _that.gridData.length; i++) {
        var datas = _that.gridData[i];
        if(id==datas.id){
          _that.$nextTick( ()=>{
            _that.$refs.multipleTable.toggleRowSelection(_that.gridData[i],false);
          })

        }
      }
    },
    // 判断权限
    checkPermission(permissionStr) {
      const _that = this
      var data = {
        permission: permissionStr
      }
      ifPermission(data).then(res => {
        // console.log(res)
        if (res.data == 1) {
          if (permissionStr == 'PlDel:admin') {
            _that.permissionFlag1 = true
          }
        }
      })
    },
    /**
     * 显示字符串中间加星号
     */
    plusXing(str, frontLen, endLen) {
      // var len = str.length - frontLen - endLen
      var xing = ''
      for (var i = 0; i < 6; i++) {
        xing += '*'
      }
      if(str.length>10){
      return str.substr(0, frontLen) + xing + str.substr(str.length - endLen)
      }else{
        return str
      }
    },

    resetForm() {
      this.search = Object.assign({}, searchForm)
      this.searchTime = [];
      this.searchTable.keyWord = "";
      this.checkClientList = [];
    },
    getList() {
      var _that = this
      var params = _that.search
      if (_that.searchTime == null || _that.searchTime < 0) {
        _that.search.beginTime = ''
        _that.search.endTime = ''
      } else {
        _that.search.beginTime = _that.searchTime[0]
        _that.search.endTime = _that.searchTime[1]
      }
      if(_that.checkClientList.length>0){
        var idsClient = []
        _that.checkClientList.forEach(item => {
          idsClient.push(item.id)
        })
        _that.search.idClients = idsClient.join(',')
      }else {
        _that.search.idClients = "";
      }
      var page = {
        pageIndex: _that.listData.page,
        pageSize: _that.listData.pageSize
      }
      var data = {
        'params': JSON.stringify(params),
        'page': JSON.stringify(page)
      }
      if (_that.listData.pageSize == 10) {
        _that.sizeType = 'medium'
      } else {
        _that.sizeType = 'mini'
      }
      // console.log(data);
      getChargeDataList(data).then(response => {
        // console.log(response)
        const data = response.data
        // //  组合表单数据
        _that.tableData = data
        _that.collection = response.collection
        _that.listData.total = response.total;
        _that.dialogTableVisible = false;
        // console.log(_that.tableData)
        _that.listLoading = false
      }).catch(err => {
        _that.dialogTableVisible = false;
        _that.$message.error(err)
        _that.listLoading = false
      })
    },

    getSummaries(param) {
      var _that = this
      const { columns, data } = param
      const sums = []
      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = '合计';
          return
        }
        if (column.label == '折扣金额') {
          sums[index] = formatMoney(_that.collection.agioMoneySum)
        } else if (column.label == '收款金额') {
          sums[index] = formatMoney(_that.collection.receivableMoneySum)
        } else {
          sums[index] = ''
        }
      })
      return sums
    },
    // 获取脚印
    getOrderStep(row) {
      const _that = this
      _that.$refs.orderStep.idOrder = row.idOrder
      _that.$refs.orderStep.getOrderStep()
    },

    // 刷新表格
    tableRefresh() {
      // 刷新变革
      this.getList()
    },

    // 点击行内任何地方选中
    handleClickTableRow(row, event, column) {
      this.$refs.orderTable.toggleRowSelection(row)
    },
    // 搜索
    searchData() {
      this.listData.page = 1
      this.getList()
    },
    // 查看订单详情
    openDetail(idOrder) {
      var _that = this
      _that.detailVisible = true
      _that.$nextTick(() => {
        _that.$refs.orderDetail.idOrder = idOrder
        _that.$refs.orderDetail.getInfo()
      })
    },
    handleSelectionChange(val) {
      // console.log(val)
      this.chosenList = val
    },
    // 批量删除收款记录
    deleteCharge() {
      var _that = this
      if (_that.chosenList.length < 1) {
        _that.$message.error('请选择收款记录')
        return
      }
      _that.deleteHtml = ''
      console.log(_that.chosenList);
      for (let i = 0; i < _that.chosenList.length; i++) {
        var dataItem = _that.chosenList[i];
        _that.deleteHtml+=dataItem.orderCode+"-"+dataItem.clientName+"；"
      }
      _that.voidVisible = true;
      _that.deleteMemo = '';
      // _that.chosenList.forEach(item => {
      //   ids.push(item.id)
      // })
      // var data = {
      //   ids: ids.join(',')
      // }
      // var url = '/order/v1/deleteChargeData'
      // _that.$refs.confirmDialog.updataClick(data, url)
    },
    deleteBtn() {
      const _that = this
      var ids = []
      _that.deleteLoader = true
      _that.chosenList.forEach(item => {
        ids.push(item.id)
      })
      var data = {
        ids: ids.join(','),
        chargeMemo: _that.deleteMemo
      }
      deleteChargeData(data).then(res =>{
        console.log(res);
        if(res.httpCode == 200){
          _that.$message.success('删除成功')
          _that.voidVisible = false
          _that.getList()
          _that.deleteLoader = false
        }
      }).catch(err =>{
        _that.deleteLoader = false
      })
    },
    // 导出
    exportBtn() {
      const _that = this
      var data = {
        code: 'OrderChargeData_Exporter',
        exportName: '收款记录导出',
        params: _that.search
      }
      exportData(data).then(res =>{
        console.log(res);
        if(res.httpCode == 200){
          _that.$message.success('导出成功，请前至系统管理-我的任务中进行查看和下载')
        }
      })
    },
    printData() {
      const _that = this;
      var PrintData = {
        '_rootData': []
      }
      if (_that.chosenList.length < 1) {
        _that.$message.error('请选择收款记录')
        return
      }
      _that.chosenList.forEach(item => {
        var data = {
          chargeMan: item.chargeMan,
          ChargeMoneyCN: changeMoneyToChinese(item.receivableMoney),
          chargeDate: item.chargeDate,
          clientName: item.clientName,
          receiveCode: item.receiveCode,
          orderCode: item.orderCode,
          financeCode: item.financeCode,
          receivableMoney: item.receivableMoney,
          accountName: item.accountName,
          orderName: item.orderName
        }
        PrintData._rootData.push(data)
      })
      // console.log(PrintData);
      // return;
      var data = {
        PrintTemplate: 'chargeorder.fr3',
        NeedPreview: 1,
        PrintData: JSON.stringify(PrintData)
      }
      // axios.post('http://127.0.0.1:19876', JSON.stringify(data), { headers: { 'Content-Type': 'application/json;charset=UTF-8' }}).then((res) => {
      //   console.log(res)
      // }).catch((error) => {
      //   console.log(error)
      // })
      // 以后打印调这个通用接口
      doLocalPrint(data)
    }
  }
}
</script>

<style lang="scss" scoped>
.filter-item{
  padding: 5px 0;
}
</style>
