<!--
  @description: 账单明细
  @Modifier：qk
  @routerPath:/reconciliation
  @date：2019/12/26
-->
<template>
  <div class="reconciliatio">
    <div class="header_box">
      <el-page-header :content="`${tabIndexList[tabIndex].name}${rowTitle}`" @back="goBack" />
    </div>
    <div class="search-content clearfix">
      <section class="fl">
        <el-form ref="reconciliatioForm" :inline="true">
          <el-form-item label="订单编号">
            <el-input v-model="value" placeholder="" />
          </el-form-item>
          <el-form-item label="发票公司名称">
            <el-input v-model="input" placeholder="" />
          </el-form-item>
          <el-form-item label="订单创建时间">
            <el-date-picker
              v-model="value1"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              value-format="timestamp"
            />
          </el-form-item>
        </el-form>
      </section>
      <div class="fr">
        <el-button type="purple" @click="searchList">
          搜索
        </el-button>
        <el-button type="gray" @click="resetList">
          重置
        </el-button>
      </div>
    </div>
    <div class="p0-16">
      <div class="nav">
        <!-- // tab对应的index 00:待对账  01:对账中  02:已对账  03:往期对账 -->
        <el-button v-if="activeName === '00'" type="purple" @click="sendClick">
          申请结算单
        </el-button>
        <el-button v-if="activeName === '00'" type="text" style="color:red;">
          请确认每笔订单已完成，再发送对账单！！！
        </el-button>
        <el-button v-if="activeName === '01'" type="text" style="color:red;">
          账单已发送，供应商核对中！
        </el-button>
        <el-button v-if="activeName === '02'" type="text" style="color:red;">
          已完成对账，发票已开出!
        </el-button>
        <el-button v-if="activeName === '03'" type="text" style="color:red;">
          往期对账单
        </el-button>
        <!-- <el-button type="purple" @click="billSubmit">
          开票
        </el-button> -->
      </div>
      <el-table
        ref="multipleTable"
        :data="tableData"
        :row-key="getRowKey"
        @selection-change="handleSelectionChange"
      >
        <el-table-column
          type="selection"
          width="55"
          align="center"
          fixed
        />
        <el-table-column
          label="序号"
          type="index"
          header-align="center"
          align="center"
          fixed
        />
        <el-table-column
          prop="supplierOrderNo"
          label="订单编号"
          header-align="center"
          min-width="160"
        />
        <el-table-column
          prop="orderNo"
          label="客户订单编号"
          header-align="center"
          min-width="160"
        />
        <el-table-column
          prop="totalAmount"
          label="订单金额（元）"
          header-align="center"
          align="right"
          min-width="120"
        />
        <el-table-column
          prop="settleAmount"
          label="结算金额（元）"
          header-align="center"
          align="right"
          min-width="120"
        />
        <el-table-column
          prop="invoiceType"
          label="发票类型"
          header-align="center"
          align="center"
        />
        <el-table-column
          prop="taxpayerIdentificationNumber"
          label="纳税人识别号"
          header-align="center"
          align="center"
          min-width="160"
        />
        <el-table-column
          prop="invoiceTitle"
          label="发票抬头"
          header-align="center"
          min-width="160"
        />
        <!-- <el-table-column
          prop="departName"
          label="发票公司名称"/>-->
        <!-- <el-table-column
          prop="createUser"
          label="创建人"
        /> -->
        <!-- // tab对应的index 00:待对账  01:对账中  02:已对账  03:往期对账 -->
        <el-table-column
          v-if="['01','02','03'].indexOf(activeName) > -1"
          prop="settleNo"
          label="结算单号"
          header-align="center"
          min-width="160"
        />
        <!-- <el-table-column
          v-if="['02','03'].indexOf(activeName) > -1"
          prop="markId"
          label="发票单号"
          min-width="160"
          header-align="center"
        /> -->
        <el-table-column
          prop="orderCreateTime"
          label="订单创建时间"
          header-align="center"
          align="center"
          min-width="160"
        />
        <el-table-column
          prop="orderCompleteTime"
          label="订单完成时间"
          header-align="center"
          align="center"
          min-width="160"
        />
        <!-- <el-table-column
          prop="checkResult"
          label="订单差异原因"
        /> -->
        <el-table-column
          label="操作"
          header-align="center"
          align="center"
          fixed="right"
        >
          <template slot-scope="scope">
            <el-link type="primary" @click="handleClick(scope.row)">
              订单详情
            </el-link>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <el-row class="pagination shopmall-pagination p16" style="clear:both;margin:20px 0">
      <div class="page-number fl">
        共{{ Math.ceil(total / infoFrom.pageSize) }}页
        {{ total }}条
      </div>
      <el-pagination
        :current-page="infoFrom.pageNo"
        :total="total"
        :page-sizes="[10,50,100]"
        class="fr"
        background
        layout="prev, pager, next, sizes"
        @current-change="pickHandle"
        @size-change="handleSizeChange"
      />
    </el-row>
    <!--添加订单-->
    <reconCiliationChildren
      v-if="reconChildren.dialog"
      :children-invoice="reconChildren"
      @watchs="watchs"
    />
    <el-dialog
      :visible.sync="differences.dialog"
      :close-on-click-modal="false"
      title="订单差异"
      width="1010px"
      custom-class="shop_mall_dialog"
    >
      <el-table
        ref="multipleTables"
        :data="tableDatadDiff"
      >
        <el-table-column
          label="序号"
          type="index"
        />
        <el-table-column
          prop="supplierOrderNo"
          label="订单编号"
        />
        <el-table-column
          prop="orderNo"
          label="客户订单编号"
        />
        <el-table-column
          prop="totalAmount"
          label="订单金额(元)"
        />
        <el-table-column
          prop="taxpayerIdentificationNumber"
          label="纳税人识别号"
        />
        <el-table-column
          prop="invoiceTitle"
          label="发票抬头"
        />
        <el-table-column
          prop="departName"
          label="发票公司名称"
        />
        <el-table-column
          prop="orderCreateTime"
          label="订单创建时间"
        />
        <el-table-column
          prop="orderCompleteTime"
          label="订单完成时间"
        />
        <el-table-column
          prop="checkResult"
          label="订单差异原因"
        />
        <el-table-column
          prop="departName"
          label="差异明细"
        />
        <el-table-column
          prop="status"
          label="差异类型"
        />
      </el-table>
      <el-row class="pagination shopmall-pagination p16" style="clear:both;margin:20px 0">
        <div class="page-number fl">
          共{{ Math.ceil(totalDiff / infoFromDiff.pageSize) }}页
          {{ totalDiff }}条
        </div>
        <el-pagination
          :current-page="infoFromDiff.pageNo"
          :total="totalDiff"
          :page-sizes="[12,24,48]"
          class="fr"
          background
          layout="prev, pager, next, sizes"
          @current-change="pickHandleDiff"
          @size-change="handleSizeChangeDiff"
        />
      </el-row>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="doneAddClickBtn">确 定</el-button>
        <el-button @click="differences.dialog = false">取 消</el-button>
      </span>
    </el-dialog>
    <el-dialog
      :visible.sync="receipt.dialog"
      :close-on-click-modal="false"
      title="发票收件管理"
      width="1010px"
      custom-class="shop_mall_dialog"
    >
      <el-table
        ref="multipleTablesc"
        :data="getBilingInfos"
        tooltip-effect="dark"
        style="width: 100%"
        @selection-change="handlereceitionChange"
      >
        >
        <el-table-column
          type="selection"
          width="55"
        />
        <el-table-column
          label="序号"
          type="index"
        />
        <el-table-column
          prop="receiverName"
          label="收件人姓名"
          min-width="100"
        />
        <el-table-column
          prop="phoneNumber"
          label="收件电话"
          min-width="80"
          align="center"
        />
        <el-table-column
          prop="address"
          label="收件地址"
          min-width="200"
        />
        <el-table-column
          prop="email"
          label="邮箱"
          min-width="100"
        />
      </el-table>
      <span slot="footer" class="dialog-footer">
        <!-- <el-button type="primary" @click="receiptClickAdd">新增收件</el-button> -->
        <el-button type="primary" @click="receiptClickBtn">确 定</el-button>
        <el-button @click="receipt.dialog = false">取 消</el-button>
      </span>
    </el-dialog>
    <!--订单详情-->
    <reconCiliaationAdds :data="childenData" />
    <el-dialog
      v-dialogDrag
      :visible.sync="statementInfoDialog"
      :close-on-click-modal="false"
      title="请填写对账单信息"
      width="50%"
      custom-class="shop_mall_dialog"
    >
      <!-- 开票方式 -->
      <div class="selectBilling">
        <span style="font-weight:700">开票方式：&nbsp;</span>
        <el-select v-model="infoSucces.billingType" clearable placeholder="请选择">
          <el-option
            v-for="item in selectionData"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </div>
      <!-- 选择发票 -->
      <div class="selectTitle">
        发票管理
        <el-link :underline="false" type="primary" @click="routerTo('/personalCenter/invoiceList')">
          <img src="@/assets/img/shopmall/settle-icon3.png">
          新增发票
        </el-link>
      </div>
      <div class="mb10 invoiceBtn">
        <img src="@/assets/img/shopmall/settle-icon1.png">
        <span @click="showconsigInvoice">
          {{ invoiceTableData.length === 0 ? '请选择' : '重新选择' }}
        </span>
      </div>
      <div v-if="invoiceTableData.length !== 0" style="padding:0 10px;">
        <el-table
          :data="invoiceTableData"
          :stripe="false"
          :border="false"
          class="shop_mall_invoiceTable"
        >
          <el-table-column label="发票抬头">
            <template slot-scope="scope">
              {{ scope.row.invoiceTitle }}
            </template>
          </el-table-column>
          <el-table-column
            prop="invoiceType"
            label="发票类型"
          />
          <el-table-column
            prop="taxpayerIdentificationNumber"
            label="发票税号"
          />
          <el-table-column
            prop="createName"
            label="发票管理员"
          />
          <el-table-column
            prop="taxpayertel"
            label="注册电话"
          />
          <el-table-column
            prop="bankname"
            label="发票开户银行"
          />
          <el-table-column
            prop="bankaccount"
            label="发票银行账号"
          />
          <el-table-column
            prop="taxpayeraddr"
            label="注册地址"
          />
        </el-table>
      </div>
      <!-- 选择收件地址 -->
      <div class="selectTitle">
        收件地址
        <el-link :underline="false" type="primary" @click="routerTo('/personalCenter/mailingaddressList')">
          <img src="@/assets/img/shopmall/settle-icon3.png">
          新增地址
        </el-link>
      </div>
      <div class="mb10 invoiceBtn">
        <img src="@/assets/img/shopmall/settle-icon1.png">
        <span @click="selectAddress">
          {{ listData.length === 0 ? '请选择' : '重新选择' }}
        </span>
      </div>
      <div v-if="listData.length !== 0" style="padding:0 10px;">
        <el-table
          :data="listData"
          tooltip-effect="dark"
          style="width: 100%"
          :stripe="false"
          :border="false"
          class="shop_mall_invoiceTable"
        >
          <el-table-column
            prop="receiverName"
            label="收件人姓名"
            min-width="80px"
          />
          <el-table-column
            prop="phoneNumber"
            label="电话号码"
            min-width="60px"
          />
          <el-table-column
            prop="address"
            label="收件地址"
            min-width="160px"
          />
          <el-table-column
            prop="email"
            label="邮箱"
            min-width="90px"
          />
        </el-table>
      </div>
      <div class="selectTitle">
        开票内容
      </div>
      <el-input
        v-model="infoSucces.invoicesContent"
        :rows="4"
        type="textarea"
        placeholder="请填写开票内容"
        maxlength="200"
        style="margin: 0 0 0 10px;width:90%"
        show-word-limit
      />
      <span slot="footer" class="dialog-footer">
        <el-button type="purple" @click="submit">确 定</el-button>
        <el-button @click="statementInfoDialog=false">取 消</el-button>
      </span>
    </el-dialog>
    <!--发票管理-->
    <addressInvoice
      v-show="childrenInvoice.dialog"
      :children-invoice="childrenInvoice"
      @childrenInvoices="childrenInvoices"
    />
  </div>
</template>
<script>
import reconCiliaationAdds from './reconCiliaation-add'
import reconCiliationChildren from './reconCiliationChildren'
// 发票管理
import addressInvoice from '../invoice/selectInvoice-dialog'
import { reconciliationDetails, sendReconciliation, getOrderDiff, getBilings } from '@/api/shoppingmall/order'
// API
import { getList } from '@/api/shoppingmall/mailingaddress'
export default {
  components: {
    reconCiliationChildren,
    reconCiliaationAdds,
    addressInvoice
  },
  props: {

  },
  data() {
    return {
      dialog: false,
      name: this.$route.query.name, // 供应商名称
      tabIndex: this.$route.query.tabIndex,
      activeName: this.$route.query.activeName,
      rowTitle: this.$route.query.rowTitle, // 对账单名称
      tabIndexList: [
        { index: '00', name: '待对账-' },
        { index: '01', name: '对账中-' },
        { index: '02', name: '已对账-' },
        { index: '03', name: '往期对账-' }
      ],
      childenData: {
        dialog: false
      },
      differences: {
        dialog: false
      },
      reconChildren: {
        dialog: false
      },
      receipt: {
        dialog: false
      },
      value1: '',
      input: '',
      options: [{
        value: '京东商城',
        label: '京东商城'
      },
      // {
      //   value: '晨光办公',
      //   label: '晨光办公'
      // },
      // {
      //   value: '固安捷',
      //   label: '固安捷'
      // },
      // {
      //   value: '震坤行',
      //   label: '震坤行'
      // },
      // {
      //   value: '史泰博',
      //   label: '史泰博'
      // },
      {
        value: '国信创新',
        label: '国信创新'
      }],
      value: '',
      tableData: [],
      infoFrom: {
        statementId: this.$route.query.id,
        settlementStatus: this.$route.query.settlementStatus,
        endDate: null,
        orderNo: null,
        pageNo: 1,
        pageSize: 10,
        startDate: null,
        supplier: null
      },
      infoFromDiff: {
        statementId: this.$route.query.id,
        endDate: null,
        orderNo: null,
        pageNo: 1,
        pageSize: 12,
        startDate: null,
        supplier: this.$route.query.name

      },
      infoSucces: {
        ids: [],
        statementId: this.$route.query.id,
        type: '',
        bilingId: '',
        checkRepeat: this.$route.query.code,
        // 开票方式
        billingType: '',
        // 开票内容
        invoicesContent: '',
        invoicesId: '' // 发票ID
      },
      tableDatad: [

      ],
      // 收件管理
      getBilingInfos: [],
      tableDatadDiff: [],
      total: 0,
      totalDiff: 0,
      // 收件地址
      listData: [],
      selectionData: [
        {
          value: '1',
          label: '集中开票'
        }, {
          value: '2',
          label: '分开开票'
        }
      ],
      // 对账单信息 弹框
      statementInfoDialog: false,
      invoiceTableData: [], // 发票数据
      // 发票弹框
      childrenInvoice: {
        dialog: false
      }
    }
  },
  computed: {
  },
  watch: {
    // 对账单信息弹框 关闭时，重置信息
    'statementInfoDialog'(val) {
      if (!val) {
        this.infoSucces.billingType = ''
        this.invoiceTableData.length = 0
        this.listData.length = 0
      }
    }
  },
  created() {
    this.initData()
    // this.infoGetOrderDiff()
    if (this.tableDatadDiff.length > 0) {
      this.open()
    }
  },
  mounted() {
  },
  methods: {
    // 保存选中的数据id,row-key就是要指定一个key标识这一行的数据
    getRowKey(row) {
      return row.orderId
    },
    // 确认发送对账单
    submit() {
      const flag = this.validateData()
      if (flag) {
        // 已勾选地址
        sendReconciliation(this.infoSucces).then(res => {
          if (res.header.ret === '0') {
            this.$message({
              type: 'success',
              message: res.data
            })
            // 关闭对账详情弹框
            this.statementInfoDialog = false
          }
        })
      }
    },
    // 验证是否填写
    validateData() {
      if (!this.infoSucces.billingType) {
        this.$message.warning('请选择开票方式！')
        return
      }
      if (!this.infoSucces.invoicesId) {
        this.$message.warning('请选择发票！')
        return
      }
      if (!this.infoSucces.bilingId) {
        this.$message.warning('请选择收件地址！')
        return
      }
      return true
    },
    // 获取收件管理列表
    getBilingskey() {
      getBilings().then(res => {
        this.getBilingInfos = res.data
      })
    },
    handleClick(item) {
      if (item.status === '00') {
        this.childenData = {
          dialog: true,
          id: item.orderId
        }
      } else {
        this.childenData = {
          dialog: true,
          id: item.orderId,
          status: item.status
        }
      }
    },
    infoGetOrderDiff() {
      getOrderDiff(this.infoFromDiff).then(res => {
        this.tableDatadDiff = res.data.records
        this.totalDiff = res.data.total
      })
    },
    open() {
      this.$confirm('本期账单存在对账差异', '提示', {
        confirmButtonText: '查看差异',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.differences.dialog = true
      }).catch(() => {
      })
    },
    initData() {
      reconciliationDetails(this.infoFrom).then(res => {
        this.tableData = res.data.records
        this.total = res.data.total
        this.initTableSelection()
      })
    },
    // 默认全部选中
    initTableSelection() {
      this.$refs.multipleTable.toggleAllSelection()
    },
    searchList() {
      if (this.value) {
        this.infoFrom.orderNo = this.value
      }
      if (this.input) {
        this.infoFrom.supplier = this.input
      }
      if (this.value1) {
        this.infoFrom.startDate = this.value1[0]
        this.infoFrom.endDate = this.value1[1]
      }
      this.initData()
    },
    resetList() {
      this.infoFrom.endDate = null
      this.infoFrom.orderNo = null
      this.infoFrom.pageNo = 1
      this.infoFrom.pageSize = 12
      this.infoFrom.startDate = null
      this.infoFrom.supplier = null
      this.value = ''
      this.input = ''
      this.value1 = ''
      this.initData()
    },
    // 收件地址 列表勾选发生变化
    handlereceitionChange(val) {
      if (val.length > 1) {
        this.$refs.multipleTablesc.clearSelection()
        this.$refs.multipleTablesc.toggleRowSelection(val.pop())
      } else {
        this.listData = val
      }
    },
    handleSelectionChange(val) {
      const obj = []
      val.forEach(ele => {
        obj.push(ele.orderId)
      })
      this.infoSucces.ids = obj
    },
    pickHandle(val) {
      this.infoFrom.pageNo = val
      this.initData()
    },
    pickHandleDiff(val) {
      this.infoFromDiff.pageNo = val
      // this.infoGetOrderDiff()
    },
    handleSizeChange(val) {
      this.infoFrom.pageNo = 1
      this.infoFrom.pageSize = val
      this.initData()
    },
    handleSizeChangeDiff(val) {
      this.infoFromDiff.pageNo = 1
      this.infoFromDiff.pageSize = val
      // this.infoGetOrderDiff()
    },
    handleClose(done) {
      this.dialog = false
    },
    // 申请结算单
    sendClick() {
      if (this.$route.query.name === '京东商城') {
        this.infoSucces.type = 'jd'
      } else {
        this.infoSucces.type = '123'
      }
      if (!this.infoSucces.ids.length) {
        this.$message({
          type: 'warning',
          message: '您没有要对账的订单'
        })
        return
      }
      // 打开对账详情弹框
      this.statementInfoDialog = true
    },
    addClick() {
      this.reconChildren.dialog = true
    },
    difference() {
      if (this.$route.query.name !== '晨光办公' || this.$route.query.name !== '震坤行') {
        if (this.tableDatadDiff.length > 0) {
          this.open()
        } else {
          this.$message({
            type: 'warning',
            message: '本期账单不存在对账差异'
          })
        }
        this.infoGetOrderDiff()
      }
    },
    doneAddClickBtn() {
      this.differences.dialog = false
    },
    watchs(val) {
      this.initData()
    },
    // 点击确定 选择收件地址
    receiptClickBtn() {
      if (this.$route.query.name === '京东商城') {
        this.infoSucces.type = 'jd'
      } else {
        this.infoSucces.type = '123'
      }
      if (!this.listData.length) {
        this.$message({
          type: 'warning',
          message: '请选择收件地址!'
        })
        return
      }
      this.infoSucces.bilingId = this.listData[0].id
      this.receipt.dialog = false
    },
    // 点击新增收件
    receiptClickAdd() {
      this.$router.push({
        path: '/personalCenter/receiptManagement',
        query: this.$route.query
      })
    },
    goBack() {
      this.$router.push({
        path: '/personalCenter/reconciliation',
        query: {
          detailIndex: this.$route.query.fromIndex
        }
      })
    },
    // 打开 选择开票方式 弹框
    billSubmit() {
      // this.handleSelectionChange()
      if (this.infoSucces.ids.length) {
        this.dialog = true
      } else {
        this.$message({
          type: 'warning',
          message: '您没有要开票的订单'
        })
      }
    },
    // 发票信息
    childrenInvoices(val) {
      this.invoiceTableData = val
      if (this.invoiceTableData.length !== 0) {
        this.infoSucces.invoicesId = val[0].id
      }
    },
    // 发票管理弹框
    showconsigInvoice() {
      this.childrenInvoice = {
        dialog: true,
        // 已选发票
        selectedInvoice: this.invoiceTableData
      }
    },
    // 打开收件地址弹框
    selectAddress() {
      // 收件地址
      // this.getBilingskey()

      // 收货地址
      getList().then(response => {
        this.getBilingInfos = response.data
      }).catch(err => {
        throw new Error('error!' + err)
      })
      this.receipt.dialog = true
    },
    // 跳转到收货地址管理/发票管理
    routerTo(path) {
      this.$router.push(path)
    }
  }
}
</script>
<style scoped lang="less">
.invoiceBtn {
  color:#1f94f4;
  cursor:pointer;
  padding-left: 10px;
  font-size: 12px;
}
.selectTitle {
  font-weight: 700;
  height: 40px;
  line-height: 40px;
  padding: 0 10px;
  display: flex;
  justify-content: space-between;
}
.selectInvoice {
  font-size: 12px;
  color: #1F88D4;
  padding-left:10px;
}
.selectBilling {
  height:60px;
  padding:10px;
  line-height: 40px;
}
.nav{
   width: 100%;
   height: 60px;
   display: flex;
   align-items: center;
   border-bottom:1px solid rgba(238, 238, 238, 1);
   .searchInput{
    width: 40%;
    display: flex;
    justify-content: flex-end;
   }
}
.header_box {
  padding: 8px 12px;
  border-bottom: 1px solid #eeeeee;
  /deep/ .el-icon-back {
    position: relative;
    left: -8px;
    top: 0;
    transition: all .2s ease;
    opacity: 0;
  }
  /deep/ .el-page-header__title {
    position: relative;
    right: 10px;
    top: 0;
    transition: all .2s ease;
  }
  /deep/ .el-page-header__left {
    &:hover {
      .el-icon-back {
        left: 3px;
        opacity: 1;
        color: #007CCC;
      }
      .el-page-header__title {
        right: 0;
        color: #007CCC;
      }
    }
  }
  /deep/.el-page-header__content {
    font-size: 14px;
    font-weight: bold;
  }
}
.shop_mall_invoiceTable {
  /deep/ th.is-leaf {
    border: none;
    padding: 5px 0;
    font-weight: 400;
  }
  /deep/ th {
    background-color: #F2F2F2;
  }
  /deep/ td {
    border-bottom: 1px solid #F2F2F2;
  }
}
</style>
