<template>
  <div class="app-container">
    <el-row class="title-style">
      <el-col :span="12">
        <h2 class="bg-left title">客户账单</h2>
      </el-col>
      <el-col :span="12" class="bg-right">
        <el-button class="bg-bottom" type="primary" size="small" @click="returnsales()">返回</el-button>
        <el-button type="primary" size="small" @click="createData">提交</el-button>
      </el-col>
    </el-row>
    <el-form
      ref="dataForm"
      :rules="rules"
      :model="dataForm"
      status-icon
      label-position="left"
      label-width="200px"
      class="position"
    >
      <div class="small-title" style="font-size: 16px">基本信息</div>
      <div class="ws-info-table">
        <el-form-item label="id" prop="id" hidden>
          <el-input v-model="dataForm.id" />
        </el-form-item>
        <el-form-item label="编号:" prop="payNo" style="margin-right:50px">
          <el-input v-model="dataForm.payNo" class="input-width" />
        </el-form-item>
        <el-form-item label="客户:" prop="customer" style="margin-right:50px">
          <el-select
            v-model="dataForm.customer"
            :disabled="isJz"
            placeholder="请选择客户"
            clearable
            size="small">
            <el-option v-for="item in khList" :label="item.customer" :value="item.customer" :key="item.customer"/>
          </el-select>
          <!-- <el-input v-model="dataForm.customer" :disabled="isJz" class="input-width"/> -->
        </el-form-item>
        <el-form-item label="单据类型:" prop="businessType" style="margin-right:50px">
          <el-select
            v-model="dataForm.businessType"
            clearable
            placeholder="请选择单据类型"
            class="input-width"
            @change="changeBusinessType"
          >
            <el-option
              v-for="item in djList"
              :label="item.label"
              :value="item.value"
              :key="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="装车日期" prop="closingDate" style="margin-right:50px">
          <el-date-picker
            v-model="dataForm.closingDate"
            :disabled="isJz"
            type="date"
            value-format="yyyy-MM-dd"
            style="width:200px"
          />
        </el-form-item>
        <el-form-item label="应付金额:" prop="amountIng" style="margin-right:50px">
          <el-input v-model="dataForm.amountIng" class="input-width" @input="priceChange"/>
        </el-form-item>
        <!-- <el-form-item label="已付金额:" prop="amountPaid" style="margin-right:50px">
          <el-input v-model="dataForm.amountPaid" class="input-width" @input="priceChange"/>
        </el-form-item> -->
        <!-- <el-form-item label="未付金额:" prop="unpaidAmount" style="margin-right:50px">
          <el-input v-model="dataForm.unpaidAmount" class="input-width" disabled/>
        </el-form-item> -->
        <el-form-item label="备注1:" prop="remarks" style="margin-right:50px">
          <el-input v-model="dataForm.remarks" class="input-width" />
        </el-form-item>
        <el-form-item label="备注2:" prop="remark" style="margin-right:50px">
          <el-input v-model="dataForm.remark" class="input-width" />
        </el-form-item>
        <!-- <el-form-item label="状态：" prop="status" style="margin-right:50px">
          <el-select v-model="dataForm.status" placeholder="请选择收款状态" clearable class="input-width">
            <el-option
              v-for="item in skList"
              :label="item.label"
              :value="item.value"
              :key="item.value"
            />
          </el-select>
        </el-form-item> -->
      </div>
      <div class="small-title" style="font-size: 16px">详情</div>
      <div style="display:flex">
        <el-button
          v-if="!isJz"
          size="mini"
          class="filter-item"
          type="primary"
          icon="el-icon-edit"
          style="margin-bottom:20px"
          @click="addDetail"
        >添加</el-button>
      </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" style="width:30px" />
        <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="cabinetNo">
          <template slot-scope="scope">
            <el-input v-model="scope.row.cabinetNo" :disabled="isJz"/>
          </template>
        </el-table-column>
        <el-table-column align="center" label="到港日期" prop="arrivalDate" width="170px">
          <template slot-scope="scope">
            <el-date-picker
              v-model="scope.row.arrivalDate"
              :disabled="isJz"
              type="date"
              value-format="yyyy-MM-dd"
              style="width:140px"
            />
          </template>
        </el-table-column>
        <el-table-column align="center" label="发货公司" prop="sendComp">
          <template slot-scope="scope">
            <el-input
              v-model="scope.row.sendComp"
              :disabled="isJz"/>
          </template>
        </el-table-column>
        <el-table-column align="center" label="车队" prop="carTeam">
          <template slot-scope="scope">
            <el-input
              v-model="scope.row.carTeam"
              :disabled="isJz"/>
          </template>
        </el-table-column>
        <el-table-column align="center" label="货品" prop="product">
          <template slot-scope="scope">
            <el-input
              v-model="scope.row.product"
              :disabled="isJz"/>
          </template>
        </el-table-column>
        <el-table-column align="center" label="目的地" prop="deliveryPlace">
          <template slot-scope="scope">
            <el-input
              v-model="scope.row.deliveryPlace"
              :disabled="isJz"/>
          </template>
        </el-table-column>
        <!-- <el-table-column align="center" label="重量" prop="weight">
          <template slot-scope="scope">
            <el-input v-model="scope.row.weight" />
          </template>
        </el-table-column> -->
        <el-table-column align="center" label="清关费" prop="clearanceFee">
          <template slot-scope="scope">
            <el-input v-model="scope.row.clearanceFee" />
          </template>
        </el-table-column>
        <el-table-column align="center" label="清关成本" prop="clearanceCost">
          <template slot-scope="scope">
            <el-input v-model="scope.row.clearanceCost" />
          </template>
        </el-table-column>
        <el-table-column align="center" label="卡车费" prop="truck">
          <template slot-scope="scope">
            <el-input v-model="scope.row.truck" />
          </template>
        </el-table-column>
        <el-table-column align="center" label="卡车成本" prop="truckCost">
          <template slot-scope="scope">
            <el-input v-model="scope.row.truckCost" />
          </template>
        </el-table-column>
        <el-table-column align="center" label="其他费用" prop="otherExpenses">
          <template slot-scope="scope">
            <el-input v-model="scope.row.otherExpenses" />
          </template>
        </el-table-column>
        <el-table-column align="center" label="其他成本" prop="otherCost">
          <template slot-scope="scope">
            <el-input v-model="scope.row.otherCost" />
          </template>
        </el-table-column>
        <el-table-column align="center" label="合计应收" prop="pricePayable">
          <template slot-scope="scope">
            <el-input v-model="scope.row.pricePayable" @input="hjys(scope.row.pricePayable)"/>
          </template>
        </el-table-column>
        <el-table-column align="center" label="合计成本" prop="cost">
          <template slot-scope="scope">
            <el-input v-model="scope.row.cost" />
          </template>
        </el-table-column>
        <el-table-column align="center" label="备注1" prop="remarks">
          <template slot-scope="scope">
            <el-input v-model="scope.row.remarks" />
          </template>
        </el-table-column>
        <el-table-column align="center" label="操作" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <el-button
              v-if="!isJz"
              type="danger"
              size="mini"
              @click.native.prevent="deleteRow(scope.$index, list)"
            >删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-form>
    <!-- 结转单据 -->
    <el-dialog :visible.sync="dialogFormVisible" title="结转单据">
      <el-form
        ref="jzDataForm"
        :model="jzDataForm"
        status-icon
        label-position="left"
        label-width="150px"
        style="width: 400px; margin-left:50px;"
      >
        <el-form-item label="客户姓名" prop>
          <el-select v-model="jzDataForm.customer" placeholder="请选择客户姓名" style="width:100%" clearable @change="getCusDateList">
            <el-option
              v-for="(item, index) in customerList"
              :label="item"
              :value="item"
              :key="index"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="装车日期" prop>
          <el-select v-model="jzDataForm.closingDate" placeholder="请选择装车日期" style="width:100%" clearable @change="getcabineNoList">
            <el-option
              v-for="(item, index) in cusDateList"
              :label="item.closingDate"
              :value="item.closingDate"
              :key="index"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="柜号" prop>
          <el-select v-model="jzDataForm.cabinetNo" placeholder="请选择柜号" style="width:100%" clearable>
            <el-option
              v-for="(item, index) in cabinetNoList"
              :label="item.cabinetNo"
              :value="item.cabinetNo"
              :key="index"
            />
          </el-select>
        </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 {
  getCusDate,
  listCustomer,
  createCustomerBillingInfo,
  updateCustomerBillingInfo,
  deleteCustomerBillingInfo
} from '@/api/customerBillingInfo'
import {
  listcustomer
} from '@/api/collectionPayment'
import Pagination from '@/components/Pagination'
export default {
  name: 'CustomerBillingInfo',
  components: { Pagination },
  data() {
    return {
      khList: [],
      khList1: [],
      fileList: [],
      appendixIdsAdd: '',
      excelFreightspace: [],
      isJz: false,
      cabinetNoList: [],
      jzDataForm: {
        cabinetNo: ''
      },
      customerList: [],
      cusDateList: [],
      djList: [
        {
          value: '1',
          label: '正常单据'
        },
        {
          value: '2',
          label: '结转单据'
        }
      ],
      skList: [
        {
          value: 1,
          label: '未收款'
        },
        {
          value: 2,
          label: '部分收款'
        },
        {
          value: 3,
          label: '已收款'
        }
      ],
      billDetailList: [
        {
          payNo: '11',
          businessType: '1',
          closingDate: '1',
          amountPaid: '1',
          unpaidAmount: '1',
          remarks: '1',
          remark: '1',
          status: '1'
        }
      ],
      list: null,
      total: 0,
      listLoading: false,
      listQuery: {
        page: 1,
        limit: 100
      },
      dataForm: {
        id: undefined,
        amountPaid: 0,
        amountIng: 0

      },
      dialogFormVisible: false,
      submiting: false,
      dialogStatus: '',
      textMap: {
        update: '编辑',
        create: '创建'
      },
      rules: {}
    }
  },
  created() {
    // this.getList()
    this.list = []
    listcustomer().then(response => {
      console.log(response)
      this.khList = response.data.data
    })
      .catch(() => {

      })
  },
  methods: {
    hjys(val) { debugger
      this.dataForm.amountIng+=Number(val)
    },
    priceChange() {
      if (this.dataForm.amountIng&&this.dataForm.amountPaid) {
        this.dataForm.unpaidAmount = Number(this.dataForm.amountIng) - Number(this.dataForm.amountPaid)
      }
    },
    getCusDateList(val) {
      this.jzDataForm.closingDate=''
      this.jzDataForm.cabinetNo=''
      console.log(val)
      const _data = {
        customer: val
      }
      getCusDate(_data)
        .then(response => {
          this.cusDateList = response.data.data
        })
        .catch(() => {
          this.list = []
          this.total = 0
          this.listLoading = false
        })
    },
    getcabineNoList(val) {
      for (let i = 0; i<this.cusDateList.length; i++) {
        if (this.cusDateList[i].closingDate==val) {
          this.cabinetNoList = this.cusDateList[i].customerBillingDetailDOList
        }
      }
    },
    changeBusinessType(e) {
      console.log(e)
      // 结转单据

      if (e == 2) {
        this.isJz = true
        this.getCustomerList()
      } else {
        this.isJz = false
      }
    },
    returnsales() {
      this.$router.push({
        path: 'customerBilling'
      })
    },
    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 == 9 ||
          index == 8 ||
          index == 10 ||
          index == 11 ||
          index == 12 ||
          index == 13 ||
          index == 14||
          index == 15
        ) {
          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] = "--";
        }
      })

      return sums
    },
    addDetail() {
      console.log('add')
      this.list.push({
        cabinetNo: '',
        arrivalDate: '',
        deliveryPlace: '',
        product: '',
        weight: '',
        clearanceFee: '',
        clearanceCost: '',
        truck: '',
        truckCost: '',
        otherExpenses: '',
        otherCost: '',
        pricePayable: '',
        cost: '',
        remarks: '',
        remark: '',
        status: ''
      })
    },
    getCustomerList() {
      listCustomer(this.listQuery)
        .then(response => {
          this.dialogFormVisible = true
          this.customerList = response.data.data
          if (response.data.data.length>0) {
            this.getCusDateList(response.data.data[0])
          }
        })
        .catch(() => {
          this.list = []
          this.total = 0
          this.listLoading = false
        })
    },
    // handleFilter() {
    //   this.listQuery.page = 1
    //   this.getList()
    // },
    resetForm() {
      this.dataForm = {
        id: undefined
      }
    },
    handleCreate() {
      this.resetForm()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    createData() {
      this.listLoading = true
      this.$refs['dataForm'].validate(valid => {
        if (valid) {
          this.submiting = true
          this.dataForm.customerBillingDetailDTOS = this.list
          createCustomerBillingInfo(this.dataForm)
            .then(response => {
              //   this.list.unshift(response.data.data)
              this.dialogFormVisible = false
              this.$notify.success({
                title: '成功',
                message: '添加成功'
              })
              this.submiting = false
              this.returnsales()
            })
            .catch(response => {
              this.$notify.error({
                title: '失败',
                message: response.data.errmsg
              })
              this.submiting = false
            })
        }
      })
    },
    handleUpdate(row) {
      this.dataForm = Object.assign({}, row)
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    updateData() {
      this.dataForm.customer = this.jzDataForm.customer
      this.dataForm.closingDate = this.jzDataForm.closingDate
      for (let i = 0; i<this.cabinetNoList.length; i++) {
        if (this.cabinetNoList[i].cabinetNo==this.jzDataForm.cabinetNo) {
          this.list =[this.cabinetNoList[i]]
        }
      }

      this.dialogFormVisible = false
      this.submiting = false
    },
    deleteRow(index, rows) {
      rows.splice(index, 1)
    },
    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.arrivalDate = v.到港日期
            obj.deliveryPlace = v.送货地点
            obj.product = v.产品
            obj.weight = v.重量
            obj.clearanceFee = v.清关费
            obj.clearanceCost = v.清关成本
            obj.truck = v.卡车
            obj.truckCost = v.卡车成本
            obj.otherExpenses = v.其他费用
            obj.pricePayable = v.应付金额
            obj.cost = v.成本价格
            obj.remarks = v.备注1
            _this.excelFreightspace.push(obj)
          })
          if (_this.excelFreightspace) {
            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)
      }
    }
  }
}
</script>
<style lang="scss">
.bg-left {
  padding-left: 30px;
}
.bg-right {
  padding-right: 10px;
  text-align: right;
}
.bg-bottom {
  margin: 15px 0px;
}
.title-style {
  background: #f6f7fc;
  border-radius: 5px;
}
.app-container {
  // background: ;
}
.title::before {
  content: "";
  display: inline-block;
  width: 5px;
  height: 30px;
  background: #5473e8;
  position: absolute;
  left: 0;
}
.position {
  position: relative;
}
.small-title {
  position: relative;
  padding: 10px;
  font-weight: 600;
  margin: 20px 0;
}
.small-title::before {
  position: absolute;
  content: "";
  display: block;
  background: #5473e8;
  width: 4px;
  height: 14px;
  left: 0px;
  top: 13px;
}
.el-form {
  padding: 0 40px;
}
.ws-info-table {
  display: -webkit-box;
  display: -ms-flexbox;
  display: flex;
  -ms-flex-wrap: wrap;
  flex-wrap: wrap;
  border-left: 1px solid #ccc;
  border-top: 1px solid #ccc;
  position: relative;
  border-left: 0;
  border-top: 0;
}
.input-width {
  width: 200px;
}
</style>
