<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input :size="sizeType" v-model.trim="search.keyWord" placeholder="关键字" style="width: 100px;" class="filter-item"/>
      <el-input :size="sizeType" v-model.trim="search.createManName" placeholder="制单人" style="width: 100px;" class="filter-item"/>
      <el-select v-model="search.validateFlag" :size="sizeType" v-if="pageType == 0 || pageType == 2">
        <el-option label="全部" value="-1"></el-option>
        <el-option label="未审核" value="0"></el-option>
        <el-option label="已审核" value="1"></el-option>
      </el-select>
      <el-select v-if="pageType == 2 || pageType == 3" style="width: 180px;" @change="dataKindChange" multiple size="mini" value-key="value" v-model="dataKindParms" placeholder="工单状态">
        <el-option
          v-for="item in options"
          :key="item.value"
          :label="item.label"
          :value="item.value">
        </el-option>
      </el-select>
      <el-select v-model="search.checkInFlag" :size="sizeType" v-if="pageType == 3 || pageType == 1">
        <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
        :size="sizeType"
        v-model="searchTime"
        type="daterange"
        range-separator="-"
        :start-placeholder="placeholderBeginTime"
        :end-placeholder="placeholderEndTime"
        format="yyyy-MM-dd"
        value-format="yyyy-MM-dd"
        :default-time="['00:00:00', '23:59:59']">
      </el-date-picker>
      <el-date-picker
        v-if="pageType==2 || pageType==3"
        :size="sizeType"
        v-model="searchTimeCorp"
        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" class="filter-item" type="primary" icon="el-icon-search" @click="searchData">
        搜索
      </el-button>
      <el-button v-if="pageType == 0 || pageType == 2" :size="sizeType" type="success" @click="validateBill()">审核</el-button>

      <el-button v-if="pageType == 1 || pageType == 3" :size="sizeType" type="danger" @click="unValidateBill()">取消审核</el-button>
      <el-button v-if="pageType == 1 || pageType == 3" :size="sizeType" type="success" @click="reconciliationBill()">对账</el-button>
      <el-button v-if="pageType == 1 || pageType == 3" :size="sizeType" type="primary" @click="exportBtn()">导出</el-button>
      <div class="top-right-btn">
        <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"
      :summary-method="getSummaries"
      show-summary
      row-key="id"
      border
      style="margin-top: 10px"
      :header-cell-style="rowCell"
      @row-click="handleClickTableRow"
      ref="orderTable"
      :row-style="customRowStyle"
      @selection-change="handleSelectionChange"
      default-expand-all>
      <el-table-column
        type="selection"
        fixed="left"
        align="center"
        :selectable="checkSelectable"
        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="操作"
        v-if="pageType == 0 || pageType == 2">
        <template slot-scope="{row}">
          <el-button
            v-if="row.billKind == 0"
            @click.stop="openAdjust(row)"
            type="primary"
            :size="sizeType">
            调账
          </el-button>
<!--          <el-button-->
<!--            @click.stop="runERP(row)"-->
<!--            type="primary"-->
<!--            :size="sizeType">-->
<!--            查看-->
<!--          </el-button>-->
        </template>
      </el-table-column>
      <el-table-column
        prop="srcBillCode"
        label="单据号"
        width="165">
        <template slot-scope="{row}">
          <el-link v-if="pageType == 1 ||pageType == 0" @click.stop="runERP(row)" type="primary">{{row.srcBillCode}}</el-link>
          <el-link v-if="pageType == 2 ||pageType == 3" @click.stop="handleDetail(row.idSrcBill,row)" type="primary">{{row.srcBillCode}}</el-link>

        </template>
      </el-table-column>
      <el-table-column
        prop="srcBillCode"
        label="单据类型"
        v-if="pageType == 1 ||pageType == 0"
        width="100">
        <template slot-scope="{row}">
          <el-tag v-if="row.idBillDefine == 6" size="mini" type="primary">纸张入库单</el-tag>
          <el-tag v-else-if="row.idBillDefine == 11" size="mini" type="success">辅料入库单</el-tag>

        </template>
      </el-table-column>
      <el-table-column
        prop="corpName"
        show-overflow-tooltip
        label="单位名称"
        width="120"></el-table-column>
      <el-table-column
        prop="dataKind"
        label="单位类型">
        <template slot-scope="{row}">
          <span v-if="row.corpType ==0">供应商</span>
          <span v-else-if="row.corpType ==1">客户</span>
          <span v-else-if="row.corpType ==2">外协</span>
          <span v-else-if="row.corpType ==3">外协辅料</span>
        </template>
      </el-table-column>

      <el-table-column
        label="制单日期"
        prop="srcBillDate"
        width="140">

        <template slot-scope="{row}">
          <span v-if="row.srcBillDate">{{ row.srcBillDate | getTime }}</span>
        </template>
      </el-table-column>
      <el-table-column
        prop="createManName"
        label="制单人"></el-table-column>
      <el-table-column
        prop="billMoney"
        width="100"
        align="right"
        label="总金额"></el-table-column>
      <el-table-column
        prop="validateManName"
        label="审核人"></el-table-column>
      <el-table-column
        prop="validateDate"
        label="审核时间"
        width="140">
        <template slot-scope="{row}">
          <span v-if="row.validateDate">{{ row.validateDate | getTime }}</span>
        </template>
      </el-table-column>
      <el-table-column
        prop="checkInManName"
        label="对账人"></el-table-column>

      <el-table-column
        prop="checkInDate"
        label="对账时间"
        width="140">
        <template slot-scope="{row}">
          <span v-if="row.checkInDate">{{ row.checkInDate | getTime }}</span>
        </template>
      </el-table-column>

      <el-table-column
        prop="checkInDate"
        :label="pageType == 0 ?'原单审核时间':'反馈时间'"
        width="140">
        <template slot-scope="{row}">
          <span v-if="row.createTime">{{ row.createTime | getTime }}</span>
        </template>
      </el-table-column>
      <el-table-column
        prop="srcBillSummary"
        width="300"
        label="摘要"></el-table-column>
      <el-table-column label="调账说明" prop="adjustMemo" 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"/>
<!--    <cancledialog @tableRefresh="tableRefresh" ref="confirmDialog"></cancledialog>-->
    <el-dialog title="调整说明" :close-on-click-modal="false" :visible.sync="collectionDialog" width="800px">
      <el-form label-width="70px" size="mini">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="原单" label-width="70px">
              <el-input
                style="width: 230px"
                v-model="adjustInfo.srcBillCode"
                disabled></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="金额" label-width="70px">
              <el-input
                style="width: 230px"
                v-model="adjustInfo.billMoney"
                disabled></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="调整金额" label-width="70px">
              <el-input-number
                style="width: 230px"
                v-model="adjustInfo.adjustMoney"></el-input-number>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="制单日期" label-width="70px">
              <el-date-picker
                style="width: 230px"
                v-model="adjustInfo.srcBillDate"
                type="date"
                value-format="yyyy-MM-dd"
                placeholder="选择日期"
                disabled>
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="22">
            <el-form-item label="调整说明" label-width="70px">
              <el-input type="textarea" v-model="adjustInfo.adjustMemo"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="collectionDialog = false">取 消</el-button>
        <el-button type="primary" @click="adjustSure">确 定</el-button>
      </div>
    </el-dialog>
    <el-dialog title="对账" :close-on-click-modal="false" :visible.sync="transDialog" width="80%">
      <el-row :gutter="20">
        <el-form label-width="70px" size="mini">
          <el-col :span="12">
            <el-form-item label="往来单位">
              <el-input v-model="transInfo.corpName" disabled></el-input>
            </el-form-item>
          </el-col>
        <el-table
          :size="sizeType"
          :data="transData"
          v-loading="listLoading"
          row-key="id"
          border
          :show-summary="true"
          style="margin-top: 10px"
          default-expand-all>
          <el-table-column
            prop="srcBillCode"
            label="单据号"
            width="120">
          </el-table-column>
          <el-table-column
            prop="corpName"
            label="单位名称"
            width="120"></el-table-column>
          <el-table-column
            prop="dataKind"
            label="单位类型">
            <template slot-scope="{row}">
              <span v-if="row.corpType ==0">供应商</span>
              <span v-else-if="row.corpType ==1">客户</span>
              <span v-else-if="row.corpType ==2">外协</span>
            </template>
          </el-table-column>

          <el-table-column
            label="制单日期"
            prop="srcBillDate"
            width="180">

            <template slot-scope="{row}">
              <span v-if="row.srcBillDate">{{ row.srcBillDate | getTime }}</span>
            </template>
          </el-table-column>
          <el-table-column
            prop="createManName"
            label="制单人"></el-table-column>
          <el-table-column
            prop="billMoney"
            align="right"
            label="总金额">
          </el-table-column>
          <el-table-column
            prop="validateManName"
            label="审核人"></el-table-column>
          <el-table-column
            prop="validateDate"
            label="审核时间">
            <template slot-scope="{row}">
              <span v-if="row.validateDate">{{ row.validateDate | getTime }}</span>
            </template>
          </el-table-column>
          <el-table-column
            prop="srcBillSummary"
            label="摘要"></el-table-column>
        </el-table>
      </el-form>
      </el-row>
      <div slot="footer" class="dialog-footer">
        <el-button @click="transDialog = false">取 消</el-button>
        <el-button type="primary" @click="checkInCorpBill">确 定</el-button>
      </div>
    </el-dialog>

    <outside-detail ref="outsideDetail"></outside-detail>
  </div>

</template>

<script>
import {
  getCorpBillStatementList,
  validateCorpBillStatement,
  adjustCorpBillStatement,
  checkInCorpBillStatementRequest,
  checkInCorpBillStatement,
  unValidateCorpBillStatement
} from '@/api/payable/auditOfStock'
import outsideDetail from '@/components/outsideDetail/outsideDetail'// 外协单详情
import Cancledialog from '@/components/Dialog/Cancledialog.vue'
import {formatMoney} from "@/filters";
import {exportData} from "@/api/orderCharge/orderCollection";
export default {
  name: 'auditOfStock',
  components: {
    Cancledialog,
    outsideDetail
  },
  data() {
    return {
      placeholderBeginTime:"",
      placeholderEndTime:"",
      dataKindParms:['2','3'],
      options: [{
        value: '2',
        label: '外协'
      }, {
        value: '3',
        label: '外协辅料'
      }],
      pageType: 0, // 0.入库单审核，1.入库单对账，2.外协单审核，3.外协单对账
      sizeType: 'mini',
      detailVisible: false,
      pluploadVisible: false,
      memoDrawer: false,
      orderStatus: '',
      search: {
        keyWord: '',
        createManName:"",
        beginTime: '',
        endTime: '',
        corpType: '',
        validateFlag: '0',
        checkInFlag: '0',
        corpBillBeginTime: '',
        corpBillEndTime: '',
      },
      searchTime: [],
      searchTimeCorp:[],
      drawer: false,
      stepList: [],
      timeString: '',

      tableData: [],

      listLoading: false,
      listData: {
        total: 0,
        page: 1,
        pageSize: 20
      },
      voidVisible: false,
      sMemo: '',
      orderId: '',
      choosedList: [],
      // 调账
      collectionDialog: false,
      adjustInfo: {
        idBill: '',
        adjustMoney: '',
        adjustMemo: '',
        srcBillCode: '',
        billMoney: '',
        srcBillDate: ''
      },

      // 对账
      transDialog: false,
      transData: [],
      transInfo: {
        corpName: ''
      },

      confirmdialog: false,
      collection:{},

    }
  },
  mounted() {
    // console.log(this.$route.fullPath.split('/').pop())
    this.pageType = this.$route.fullPath.split('/').pop()
    console.log(this.pageType);
    if (this.pageType == 0 || this.pageType == 1) {
      this.search.corpType = 0;
      this.placeholderBeginTime = "开始日期";
      this.placeholderEndTime = "开始日期";
      // this.search.valiedateFlag = 0
    } else if (this.pageType == 2 || this.pageType == 3) {
      this.search.corpType = "2,3";
      this.placeholderBeginTime = "外协制单开始日期";
      this.placeholderEndTime = "外协制单结束日期";
    }
    this.getList()
  },
  methods: {
    dataKindChange(val){
      var _that = this;
      _that.dataKindParms = val;
      // console.log(_that.dataKindParms);
      var ids = [];
      if (_that.dataKindParms.length>0) {

        for (let i = 0; i <_that.dataKindParms.length; i++) {
          var datas = _that.dataKindParms[i];
          ids.push(datas)
        }
        var idRemotes = ids.join(',');

        _that.search.corpType = idRemotes;
      }else {
        _that.search.corpType = "2,3";
      }
    },
    // 勾选置灰
    checkSelectable(row) {
      // console.log(row);
      if (this.pageType == 0 || this.pageType == 2) {
        if (row.validateFlag == 1) {
          return false
        } else {
          return true
        }
      } else if (this.pageType == 3 || this.pageType == 1) {
        if (row.checkInFlag == 1) {
          return false
        } else {
          return true
        }
      }
    },
    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.pageType == 2 || _that.pageType == 3) {
        if (_that.searchTimeCorp == null || _that.searchTimeCorp < 0) {
          _that.search.corpBillBeginTime = ''
          _that.search.corpBillEndTime = ''
        } else {
          _that.search.corpBillBeginTime = _that.searchTimeCorp[0]
          _that.search.corpBillEndTime = _that.searchTimeCorp[1]
        }
      }
      if (_that.pageType == 1 || _that.pageType == 3) {
        _that.search.validateFlag = '1'
      }
      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);
      // return
      getCorpBillStatementList(data).then(response => {
        // console.log(response)
        const data = response.data
        // //  组合表单数据
        _that.tableData = data
        _that.listData.total = response.total
        _that.collection = response.collection
        // console.log(_that.tableData)
        _that.listLoading = false
      }).catch(err => {
        _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.billMoneySum)
        } else {
          sums[index] = ''
        }
      })
      return sums
    },
    customRowStyle({row, rowIndex}) {
      if (row.billKind == 1) {
        return {
          background: '#f7b1b1'
        }
      }
    },

    // 导出
    exportBtn() {
      const _that = this
      var exportName = ''
      if(_that.pageType == 1){
        exportName = '入库单对账导出'
      }else if(_that.pageType == 3){
        exportName = '外协单对账导出'
      }
      var data = {
        code: 'CorpBillStatement_Exporter',
        exportName: exportName,
        params: _that.search
      }
      exportData(data).then(res =>{
        // console.log(res);
        if(res.httpCode == 200){
          _that.$message.success('导出成功，请前至系统管理-我的任务中进行查看和下载')
        }
      })
    },

    // 滑到底部时进行加载
    load() {
      this.listLoading = true
      setTimeout(() => {
        this.listData.page += 1 // 页数+1
        // if(this.tableData.length >= this.listData.total){
        //   return
        // }
        // console.log(this.listData.page);
        this.getList() // 调用接口，此时页数+1，查询下一页数据
      }, 1000)
    },
    // 搜索
    searchData() {
      this.listData.page = 1
      this.getList()
    },
    handleSelectionChange(val) {
      console.log(val)
      this.choosedList = val
    },

    // 刷新变革
    tableRefresh() {
      // 刷新变革
      this.getList()
    },
    // 点击行内任何地方选中
    handleClickTableRow(row, event, column) {
      if (this.pageType == 0 || this.pageType == 2) {
        if (row.validateFlag == 0) {
          this.$refs.orderTable.toggleRowSelection(row)
        }
      }else if (this.pageType == 3 || this.pageType == 1) {
        if (row.checkInFlag == 0) {
          this.$refs.orderTable.toggleRowSelection(row)
        }
      }
    },
    // 审核
    validateBill() {
      var _that = this
      var ids = []
      if (_that.choosedList.length < 1) {
        _that.$message.error('请选择单据')
        return
      }
      _that.choosedList.forEach(item => {
        ids.push({ id: item.id })
      })
      var data = {
        'billList': JSON.stringify(ids)
      }
      // console.log(data)
      // return
      validateCorpBillStatement(data).then(response => {
        console.log(response)
        if (response.httpCode == 200) {
          _that.$message.success('审核成功')
          setTimeout(function() {
            _that.tableRefresh()
          }, 1500)
        } else {
          _that.$message.error(response.msg)
        }
      }).catch(err => {
        _that.$message.error(err)
      })
    },
    // 取消审核
    unValidateBill() {
      var _that = this
      var ids = []
      if (_that.choosedList.length < 1) {
        _that.$message.error('请选择单据')
        return
      }
      _that.choosedList.forEach(item => {
        ids.push({ id: item.id })
      })
      var data = {
        'billList': JSON.stringify(ids)
      }
      // console.log(data)
      // return
      unValidateCorpBillStatement(data).then(response => {
        console.log(response)
        if (response.httpCode == 200) {
          _that.$message.success('取消审核成功')
          _that.tableRefresh()
        } else {
          _that.$message.error(response.msg)
        }
      }).catch(err => {
        _that.$message.error(err)
      })
    },
    // 开始调账
    openAdjust(row) {
      var _that = this
      _that.collectionDialog = true
      _that.adjustInfo = {
        idBill: row.id,
        adjustMoney: row.adjustMoney,
        adjustMemo: row.adjustMemo,
        srcBillCode: row.srcBillCode,
        billMoney: row.billMoney,
        srcBillDate: row.srcBillDate
      }
    },
    // 调整确定
    adjustSure() {
      var _that = this
      // console.log(typeof _that.adjustInfo.adjustMoney);
      if (_that.adjustInfo.adjustMoney == 0) {
        _that.$message.error('调整金额不能为0')
        return
      }
      if(!_that.adjustInfo.adjustMemo){
        _that.$message.error('调整说明不能为空')
        return
      }
      var data = {
        'idBill': _that.adjustInfo.idBill,
        'adjustMoney': JSON.stringify(_that.adjustInfo.adjustMoney),
        'adjustMemo': _that.adjustInfo.adjustMemo
      }
      // return
      adjustCorpBillStatement(data).then(response => {
        console.log(response)
        if (response.httpCode == 200) {
          // _that.recordList = []
          // _that.multiChargeList = []
          _that.collectionDialog = false
          _that.$message.success('调整成功')
          _that.tableRefresh()
        } else {
          _that.$message.error(response.msg)
        }
      }).catch(err => {
        _that.$message.error(err)
      })
    },

    // 对账
    reconciliationBill() {
      var _that = this
      var ids = []
      console.log(_that.choosedList)
      if (_that.choosedList.length < 1) {
        _that.$message.error('请选择单据')
        return
      }
      _that.choosedList.forEach(item => {
        ids.push(item.id)
      })
      var data = {
        'idList': JSON.stringify(ids)
      }
      // console.log(data)
      // return
      checkInCorpBillStatementRequest(data).then(response => {
        console.log(response)
        if (response.httpCode == 200) {
          _that.transDialog = true
          _that.transInfo.corpName = response.data.corpName
          _that.transData = response.data.billStatementList
        } else {
          _that.$message.error(response.msg)
        }
      }).catch(err => {
        _that.$message.error(err)
      })
    },
    // 对账确认
    checkInCorpBill() {
      var _that = this
      var billList = []
      _that.transData.forEach(item => {
        billList.push(
          {
            id: item.id,
            idCorp: item.idCorp
          })
      })
      var data = {
        'billList': JSON.stringify(billList)
      }
      // console.log(data)
      // return
      checkInCorpBillStatement(data).then(response => {
        console.log(response)
        if (response.httpCode == 200) {
          _that.$message.success('对账成功')
          _that.transDialog = false
          setTimeout(function() {
            _that.tableRefresh()
          }, 1500)
          // _that.transInfo.corpName = response.data.corpName
          // _that.transData = response.data.billStatementList
        } else {
          _that.$message.error(response.msg)
        }
      }).catch(err => {
        _that.$message.error(err)
      })
    },
    runERP(row) {
      var _that = this
      var userAgent = navigator.userAgent
      if (userAgent.indexOf('DnyERPBrowser') > 0) {
        var data = {
          package: 'dyInventoryPlugin',
          runParam: 'Form:ShowModal:TfrmStockBill_Update_StockIn@' + row.idBillDefine + ',' + row.idSrcBill + ',View'
        }

        dyERP.sendRunForm(JSON.stringify(data))
      } else {
        _that.$message({
          message: '请使用开发商提供的ERP客户端',
          type: 'warning'
        })
      }
    },
    rowCell() {
      return 'text-align:center;'
    },
    handleDetail(id,row) {
      const _that = this;
      // console.log("111",row);
      _that.$refs.outsideDetail.idOrder = id
      _that.$refs.outsideDetail.dialogVisible = true
      _that.$refs.outsideDetail.getOutsideDetail()
    }
  }
}
</script>
<style>
/*1.显示滚动条：当内容超出容器的时候，可以拖动：*/
.el-drawer__body {
  overflow: auto;
}
.stepList .el-card__body{
  padding: 10px;
}
:focus{
  outline:0;
}
</style>

<style scoped>
.filter-container {
  margin-bottom: 15px;
}
</style>
