<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input
        v-model="listQuery.type.payNo"
        clearable
        class="filter-item"
        size="small"
        style="width: 200px;"
        placeholder="请输入编号" />
      <el-select
        v-model="listQuery.type.customer"
        placeholder="请选择客户"
        style="margin:0 20px;"
        clearable
        size="small">
        <el-option v-for="item in khList" :label="item.customer" :value="item.customer" :key="item.customer"/>
      </el-select>
      <!-- <el-select v-model="listQuery.type.status" size="small" clearable placeholder="请选择收款状态">
        <el-option
          v-for="item in skList"
          :label="item.label"
          :value="item.value"
          :key="item.value"
        />
      </el-select> -->
      <el-select
        v-model="listQuery.type.businessType"
        placeholder="请选择单据类型"
        style="margin:0 20px;"
        size="small">
        <el-option v-for="item in djList" :label="item.label" :value="item.value" :key="item.value"/>
      </el-select>
      <el-date-picker
        v-model="selectDate"
        style="margin-right:20px"
        size="small"
        type="daterange"
        value-format="yyyy-MM-dd"
        range-separator="至"
        start-placeholder="开始日期"
        end-placeholder="结束日期"/>
      <el-button
        v-permission="['customerBilling:customerbilling:list']"
        class="filter-item"
        type="primary"
        size="mini"
        icon="el-icon-search"
        @click="handleFilter">查找</el-button>
      <el-button
        v-permission="['customerBilling:customerbilling:create']"
        class="filter-item"
        type="primary"
        size="mini"
        icon="el-icon-edit"
        @click="handleCreate">添加</el-button>
      <el-button
        class="filter-item"
        type="primary"
        size="mini"
        icon="el-icon-edit"
        @click="exportlist">导出</el-button>
      <el-upload
        :on-change="importClick"
        :show-file-list="false"
        :auto-upload="false"
        style="margin-left: 8px;margin-bottom:0"
        class="filter-item"
        action=""
        accept=".csv, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel">
        <el-button
          class="filter-item"
          type="primary"
          icon="el-icon-edit">导入</el-button>
      </el-upload>
    </div>

    <el-table
      v-loading="listLoading"
      :data="list"
      :summary-method="getSummaries"
      size="small"
      element-loading-text="正在查询中。。。"
      border
      fit
      highlight-current-row
      show-summary
      @selection-change="handleSelectionChange">
      <el-table-column :selectable="selectInit" type="selection"/>
      <el-table-column type="index" label="序号">
        <template scope="scope">
          <span v-if="scope.$index < 9">0{{ scope.$index + 1 }}</span>
          <span v-else>{{ scope.$index + 1 }}</span>
        </template>
      </el-table-column>

      <el-table-column align="center" label="编号" prop="payNo" />
      <el-table-column align="center" label="客户" prop="customer" />
      <el-table-column align="center" label="单据类型" prop="businessType">\
        <template slot-scope="scope">
          {{ scope.row.businessType==1?'正常单据':'结转单据' }}
        </template>
      </el-table-column>
      <el-table-column align="center" label="装车日期" prop="closingDate" />
      <el-table-column align="center" label="应付金额" prop="amountIng" />
      <!-- <el-table-column align="center" label="已付金额" prop="amountPaid" /> -->
      <!-- <el-table-column align="center" label="未付金额" prop="unpaidAmount" /> -->
      <el-table-column align="center" label="备注1" prop="remarks" />
      <el-table-column align="center" label="备注2" prop="remark" />
      <!-- <el-table-column align="center" label="状态" prop="status"> -->
      <!-- <template slot-scope="scope">
        <span v-if="scope.row.status==1">
          未收款
        </span>
        <span v-if="scope.row.status==2">
          部分收款
        </span>
        <span v-if="scope.row.status==3">
          已收款
        </span>
      </template>
      </el-table-column> -->
      <el-table-column align="center" label="操作" class-name="small-padding" width="250px">
        <template slot-scope="scope">
          <el-button
            v-permission="['customerBilling:customerbilling:edit']"
            type="primary"
            size="mini"
            @click="handleLook(scope.row)">查看</el-button>
          <el-button
            v-permission="['customerBilling:customerbilling:edit']"
            type="primary"
            size="mini"
            @click="handleUpdate(scope.row)">编辑</el-button>
          <el-button
            v-permission="['customerBilling:customerbilling:delete']"
            type="danger"
            size="mini"
            @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination
      :current-page="currentPage"
      :page-sizes="[100, 200, 300, 400,1000,1500,2000]"
      :page-size="100"
      :total="total"
      layout="total, sizes, prev, pager, next, jumper"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"/>

    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form
        ref="dataForm"
        :rules="rules"
        :model="dataForm"
        status-icon
        label-position="left"
        label-width="100px"
        style="width: 400px; margin-left:50px;">
        <el-form-item label="id" prop="id" hidden>
          <el-input v-model="dataForm.id" />
        </el-form-item>
        <el-form-item label="编号" prop="payNo">
          <el-input v-model="dataForm.payNo" />
        </el-form-item>
        <el-form-item label="单据类型" prop="businessType">
          <el-input v-model="dataForm.businessType" />
        </el-form-item>
        <el-form-item label="装车日期" prop="closingDate">
          <el-input v-model="dataForm.closingDate" />
        </el-form-item>
        <!-- <el-form-item label="已付金额" prop="amountPaid">
          <el-input v-model="dataForm.amountPaid" />
        </el-form-item> -->
        <!-- <el-form-item label="未付金额" prop="unpaidAmount">
          <el-input v-model="dataForm.unpaidAmount" />
        </el-form-item> -->
        <el-form-item label="备注1" prop="remarks">
          <el-input v-model="dataForm.remarks" />
        </el-form-item>
        <el-form-item label="备注2" prop="remark">
          <el-input v-model="dataForm.remark" />
        </el-form-item>
        <!-- <el-form-item label="状态" prop="status">
          <el-input v-model="dataForm.status" />
        </el-form-item> -->
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button v-if="dialogStatus == 'create'" :loading="submiting" type="primary" @click="createData">确定
        </el-button>
        <el-button v-else :loading="submiting" type="primary" @click="updateData">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  dayjs
} from 'base-core-lib'
import {
  importWord,
  listCustomerBillingInfo,
  createCustomerBillingInfo,
  updateCustomerBillingInfo,
  deleteCustomerBillingInfo,
  exportXlsx
} from '@/api/customerBillingInfo'
import {
  listcustomer
} from '@/api/collectionPayment'
import Pagination from '@/components/Pagination'
export default {
  name: 'CustomerBillingInfo',
  components: { Pagination },
  data() {
    return {
      isAllowExport: true,
      khList: [],
      khList1: [],
      skList: [
        {
          value: 1,
          label: '未收款'
        },
        {
          value: 2,
          label: '部分收款'
        },
        {
          value: 3,
          label: '已收款'
        }
      ],
      modification: [],
      selectDate: '',
      djList: [
        {
          value: '1',
          label: '正常单据'
        },
        {
          value: '2',
          label: '结转单据'
        }
      ],
      list: null,
      total: 0,
      listLoading: true,
      listQuery: {
        page: 1,
        limit: 100,
        type: {}
      },
      dataForm: {
        id: undefined
      },
      dialogFormVisible: false,
      submiting: false,
      dialogStatus: '',
      textMap: {
        update: '编辑',
        create: '创建'
      },
      rules: {
      }
    }
  },
  created() {
    this.getList()
    this.currentPage = 1
  },
  methods: {
    importClick(file, fileList) {
      this.fileTemp = file.raw
      const fileName = file.raw.name
      const fileType = fileName.substring(fileName.lastIndexOf('.') + 1)
      // 判断上传文件格式
      if (this.fileTemp) {
        if (fileType == 'xlsx' || fileType == 'xls') {
          this.importf(this.fileTemp)
        } else {
          this.$message({
            type: 'warning',
            message: '附件格式错误，请删除后重新上传！'
          })
        }
      } else {
        this.$message({
          type: 'warning',
          message: '请上传附件！'
        })
      }
    },
    importf(obj) {
      this.excelFreightspace = []
      // this.dialogVisible = true;
      const _this = this
      const inputDOM = this.$refs.inputer // 通过DOM取文件数据
      this.file = event.currentTarget.files[0]
      var rABS = false // 是否将文件读取为二进制字符串
      var f = this.file
      var reader = new FileReader()
      // if (!FileReader.prototype.readAsBinaryString) {
      FileReader.prototype.readAsBinaryString = function (f) {
        var binary = ''
        var rABS = false // 是否将文件读取为二进制字符串
        var pt = this
        var wb // 读取完成的数据
        var outdata
        var reader = new FileReader()
        reader.onload = function (e) {
          var bytes = new Uint8Array(reader.result)
          var length = bytes.byteLength
          for (var i = 0; i < length; i++) {
            binary += String.fromCharCode(bytes[i])
          }
          var XLSX = require('xlsx')
          if (rABS) {
            wb = XLSX.read(btoa(fixdata(binary)), { // 手动转化
              type: 'base64',
              cellDates: true
            })
          } else {
            wb = XLSX.read(binary, {
              type: 'binary'
            })
          }
          // outdata就是你想要的东西 excel导入的数据
          outdata = XLSX.utils.sheet_to_json(wb.Sheets[wb.SheetNames[0]])
          // excel 数据再处理
          const arr = []
          outdata.map(v => {
            // let jsonString = JSON.stringify(v).replace(/\*/g, '').replace(/\s/ig,'');
            const jsonString = JSON.stringify(v).replace(/\//g, '').replace(/\s/ig, '')
            v = JSON.parse(jsonString)
            const obj = {}
            // xxx代表列名
            obj.cabinetNo = v.柜号
            obj.customer = v.客户
            obj.arrivalDate = v.到港日期
            obj.closingDate = v.装车日期
            obj.deliveryPlace = v.目的地
            obj.product = v.货品
            obj.clearanceFee = v.清关费
            obj.clearanceCost = v.清关成本
            obj.truck = v.卡车费
            obj.truckCost = v.卡车成本
            obj.otherExpenses = v.其他费用
            obj.otherCost = v.其他成本
            obj.pricePayable = v.合计应收
            obj.cost = v.合计成本
            obj.sendComp = v.发货公司
            obj.carTeam = v.车队
            for (let i = 0; i < _this.khList.length; i++) {
              _this.khList1.push(_this.khList[i].customer)
            }
            if (!_this.khList1.includes(obj.customer)) {
              _this.isAllowExport = false
              _this.$notify({
                title: '失败',
                message: '导入失败，导入数据中客户不存在，请重新编辑',
                type: 'error'
              })
              return
            } else {
              // _this.excelFreightspace.push(obj)
              _this.isAllowExport = true
            }
            _this.excelFreightspace.push(obj)
          })
          if (_this.excelFreightspace && _this.isAllowExport) {
            importWord(_this.excelFreightspace).then((response) => {
              if (response.status == '200') {
                _this.$notify({
                  title: '成功',
                  message: '导入成功',
                  type: 'success'
                })
                _this.getList()
              }
            })
          }
        }
        reader.readAsArrayBuffer(f)
      }
      if (rABS) {
        reader.readAsArrayBuffer(f)
      } else {
        reader.readAsBinaryString(f)
      }
    },
    async exportlist() {
      if (this.modification.length == 0) {
        this.$message.warning('请选择要导出的条目！')
      } else {
        console.log('导出数据', this.modification)
        const _data = {
          customerBillingInfoDTOS: this.modification
        }
        const {
          data
        } = await exportXlsx(_data).then((response) => {
          this.download(response.data.data)
          if (response.status == '200') {

          }
        })
      }
    },
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`)
      this.listQuery.limit = val
      this.getList()
    },
    handleCurrentChange(val) {
      this.listQuery.page = val
      console.log(`当前页: ${val}`)
      this.getList()
    },
    handleSelectionChange(val) {
      this.modification = val
    },
    selectInit(row) {
      return true
    },
    getSummaries(param) {
      const { columns, data } = param
      const sums = []
      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = '合计'
          return
        } else if (
          index == 6
        ) {
          const values = data.map(item => Number(item[column.property]))
          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] += ''
          } else {
            sums[index] = '--'
          }
        } else {
          // sums[index] = "--";
        }
      })
      if (sums.length>0) {
        sums[6] = Number(sums[6]).toFixed(2)
      }
      return sums
    },
    getList() {
      this.listLoading = true
      if (this.selectDate&&this.selectDate.length > 0) {
        this.listQuery.type.startDate = dayjs(this.selectDate[0]).format('YYYY-MM-DD')
        this.listQuery.type.endDate = dayjs(this.selectDate[1]).format('YYYY-MM-DD')
      } else {
        this.listQuery.type.startDate = ''
        this.listQuery.type.endDate = ''
      }
      listCustomerBillingInfo(this.listQuery).then(response => {
        this.list = response.data.data.items
        this.total = response.data.data.total
        this.listLoading = false
      })
        .catch(() => {
          this.list = []
          this.total = 0
          this.listLoading = false
        })
      listcustomer().then(response => {
        console.log(response)
        this.khList = response.data.data
      })
        .catch(() => {

        })
    },
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    resetForm() {
      this.dataForm = {
        id: undefined
      }
    },
    handleLook(row) {
      this.$router.push({
        path: 'customerBillingInfolook',
        query: {
          id: row.id
        }
      })
    },
    handleCreate() {
      this.$router.push({
        path: 'customerBillingInfoadd'
      })
    },
    createData() {
      this.$refs['dataForm'].validate(valid => {
        if (valid) {
          this.submiting = true
          createCustomerBillingInfo(this.dataForm).then(response => {
            this.list.unshift(response.data.data)
            this.dialogFormVisible = false
            this.$notify.success({
              title: '成功',
              message: '添加成功'
            })
            this.submiting = false
          })
            .catch(response => {
              this.$notify.error({
                title: '失败',
                message: response.data.errmsg
              })
              this.submiting = false
            })
        }
      })
    },
    handleUpdate(row) {
      this.$router.push({
        path: 'customerBillingInfoedit',
        query: {
          id: row.id
        }
      })
      // this.dataForm = Object.assign({}, row)
      // this.dialogStatus = 'update'
      // this.dialogFormVisible = true
      // this.$nextTick(() => {
      //     this.$refs['dataForm'].clearValidate()
      // })
    },
    updateData() {
      this.$refs['dataForm'].validate(valid => {
        if (valid) {
          this.submiting = true
          updateCustomerBillingInfo(this.dataForm).then(() => {
            for (const v of this.list) {
              if (v.id === this.dataForm.id) {
                const index = this.list.indexOf(v)
                this.list.splice(index, 1, this.dataForm)
                break
              }
            }
            this.dialogFormVisible = false
            this.submiting = false
            this.$notify.success({
              title: '成功',
              message: '更新成功'
            })
          })
            .catch(response => {
              this.$notify.error({
                title: '失败',
                message: response.data.errmsg
              })
              this.submiting = false
            })
        }
      })
    },
    handleDelete(row) {
      this.$confirm('此操作将永久删除该记录---' + row.id + '---, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteCustomerBillingInfo(row.id).then(response => {
          this.$notify.success({
            title: '成功',
            message: '删除成功'
          })
          const index = this.list.indexOf(row)
          this.list.splice(index, 1)
        })
          .catch(response => {
            this.$notify.error({
              title: '失败',
              message: response.data.errmsg
            })
          })
      }).catch(() => {
        return false
      })
    }
  }
}
</script>
