<template>
  <div class="app-container">
    <!-- 搜索 -->
    <div class="filter-container">
      <el-form :inline="true" :model="searchForm">
        <el-form-item label="供应商名称" >
          <el-input v-model="searchForm.supplier_name" placeholder="请输入供应商名称" />
        </el-form-item>
         <el-form-item>
          <el-date-picker
            v-model="searchForm.account_date"
            type="month"
            placeholder="选择月"
            :picker-options="pickerOptions"
            value-format="yyyy-MM">
          </el-date-picker>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" @click="fetchData">搜索</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-download" @click="handleDownload">导出</el-button>
        </el-form-item>
      </el-form>
    </div>
    <!-- 表格 -->
    <div class="mb-10 f700">供应商总数：{{total}}</div>
    <el-table v-loading="listLoading" 
      :data="firmList" border fit 
      :span-method="objectSpanMethod" 
      highlight-current-row :height="clientHeight-184"
      style="width: 100%;">
      <!-- <el-table-column label="ID" prop="supplier_id" align="center" width="80"></el-table-column> -->
      <el-table-column label="供应商编号" prop="supplier_num" align="center"></el-table-column>
      <el-table-column label="供应商名称" prop="supplier_name" align="center" width="200"></el-table-column>
      <!-- 有公共部分开始 -->
      <el-table-column label="类型" prop="product_type" align="center">
        <template slot-scope="scope">{{getProductType(scope.row.product_type)}}</template>
      </el-table-column>
      <el-table-column label="品种" prop="variety_num" align="center"></el-table-column>
      <el-table-column label="出厂数量(吨)" prop="order_ton" align="center"></el-table-column>
      <el-table-column label="单价(元)" prop="order_fee" align="center"></el-table-column>
      <el-table-column label="总额(元)" prop="sum_fee" align="center"></el-table-column>
      <!-- 有公共部分结束 -->
      <el-table-column label="应付" prop="should_fee" align="center"></el-table-column>
      <el-table-column label="已付" prop="already_pay" align="center"></el-table-column>
      <el-table-column label="总欠款" prop="owe_sum" align="center"></el-table-column>
      <el-table-column label="预付款" prop="init_pay" align="center"></el-table-column>
      <el-table-column label="操作" align="center" width="200">
        <template slot-scope="scope" v-if="scope.row.supplier_num!='合计'">
          <el-button size="mini" type="primary" @click="goDetail(scope.row.supplier_id)"> 付款明细 </el-button>
          <el-button size="mini" type="primary" @click="handleType(scope.row.supplier_id)"> 付款记账 </el-button>
        </template>
      </el-table-column>     
    </el-table>
    <!-- 翻页 -->
    <!-- <pagination v-show="total>0" 
      :total="total" 
      :page.sync="searchForm.page" 
      :page_len.sync="searchForm.page_len"
      :limit.sync="searchForm.limit" 
      @pagination="fetchData" /> -->
    <!-- 备注弹窗 -->
    <el-dialog :title="textMap[dialogType]" :visible.sync="dialogEntry" center width="400px" @close="closeDialog">
      <div class="flex flex-justify-spacearound" v-if="dialogType=='type'">
        <el-button size="mini" type="primary" @click="dialogType='draft'"> 汇票 </el-button>
        <el-button size="mini" type="primary" @click="dialogType='cash'"> 现金 </el-button>
      </div>
      <el-form :model="entryInfo" label-width="100px" :rules="formRules" ref="postForm" v-if="dialogType!='type'">
        <el-form-item label="入账时间：" prop="input_time">
          <el-date-picker
            v-model="entryInfo.input_time"
            type="datetime"
            placeholder="请选择时间"
            value-format="yyyy-MM-dd HH:mm:ss"/>
        </el-form-item>
        <el-form-item label="转账明细：" prop="draft_detail" v-if="dialogType=='draft'">
          <el-input v-model="entryInfo.draft_detail" placeholder="请输入转账明细"/>
        </el-form-item>
        <el-form-item label="票号：" prop="draft_num" v-if="dialogType=='draft'">
          <el-input v-model="entryInfo.draft_num" placeholder="请输入票号"/>
        </el-form-item>
        <el-form-item label="票据类型：" prop="draft_type" v-if="dialogType=='draft'">
          <el-select v-model="searchForm.draft_type" placeholder="请选择" @change="getDraftType" clearable>
            <el-option label="纸票" value="type-00"></el-option>
            <el-option label="电票" value="type-01"></el-option>
            <el-option label="商票" value="type-02"></el-option>
            <el-option label="现金" value="type-03"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="金额：" prop="order_fee">
          <el-input v-model="entryInfo.order_fee" placeholder="请输入金额"/>
        </el-form-item>
        <el-form-item label="出票日：" prop="output_date" v-if="dialogType=='draft'">
          <el-date-picker
            v-model="entryInfo.output_date"
            type="datetime"
            placeholder="请选择时间"
            value-format="yyyy-MM-dd HH:mm:ss"/>
        </el-form-item>
        <el-form-item label="到期日：" prop="expire_date" v-if="dialogType=='draft'">
          <el-date-picker
            v-model="entryInfo.expire_date"
            type="datetime"
            placeholder="请选择时间"
            value-format="yyyy-MM-dd HH:mm:ss"/>
        </el-form-item>
        <el-form-item label="备注：" prop="draft_note" v-if="dialogType=='draft'">
          <!-- <el-input v-model="entryInfo.draft_note" placeholder="请输入备注 "/> -->
          <el-input
            type="textarea"
            :rows="4"
            placeholder="请输入备注"
            v-model="entryInfo.draft_note">
          </el-input>
        </el-form-item>

        <!-- <el-form-item label="开票时间：" prop="cash_date" v-if="dialogType=='cash'">
          <el-date-picker
            v-model="entryInfo.cash_date"
            type="datetime"
            placeholder="请选择时间"
            value-format="yyyy-MM-dd HH:mm:ss"/>
        </el-form-item> -->
        <el-form-item label="转账明细：" prop="cash_detail" v-if="dialogType=='cash'">
          <el-input v-model="entryInfo.cash_detail" placeholder="请输入转账明细"/>
        </el-form-item>
        <!-- <el-form-item label="开票金额：" prop="cash_fee" v-if="dialogType=='cash'">
          <el-input v-model="entryInfo.cash_fee" placeholder="请输入开票金额"/>
        </el-form-item> -->
        <el-form-item label="备注：" prop="cash_note" v-if="dialogType=='cash'">
          <!-- <el-input v-model="entryInfo.cash_note" placeholder="请输入备注"/> -->
          <el-input
            type="textarea"
            :rows="4"
            placeholder="请输入备注"
            v-model="entryInfo.cash_note">
          </el-input>
        </el-form-item>
        <el-button style="margin-left:140px" type="primary" @click="submitForm">保存</el-button>
      </el-form>
    </el-dialog>
  </div>
</template>


<script>
import { listSupplierAccount, saveDraft, saveCash, exportSupplier } from '@/api/order/index'
import { checkRqInput, checkNum } from '@/utils/validate'
import { baseUrl } from '@/utils/env.js'

export default {
  data() {
    return {
      firmList: [],  // 列表
      total: 0,  // 总数
      listLoading: true,
      textMap: {
        type: '请选择记账模式',
        draft: '请输入汇票记账信息',
        cash: '请输入现金记账信息',
      }, // title匹配
      dialogType: false, // 控制title
      dialogEntry:false, // 选择汇票/现金
      entryInfo: {},
      supplier_id: '',
      // 校验规则
      formRules: {
        input_time: [ checkRqInput ],
        draft_detail: [ checkRqInput ],
        draft_num: [ checkRqInput ],
        draft_type: [ checkRqInput ],
        order_fee: [ checkRqInput, checkNum ],
        output_date: [ checkRqInput ],
        expire_date: [ checkRqInput ],
        draft_note: [ checkRqInput ],
        cash_date: [ checkRqInput ],
        cash_detail: [ checkRqInput ],
        cash_fee: [ checkRqInput, checkNum ],
        cash_note: [ checkRqInput ],
      },
      // 搜索相关数据
      searchForm: {
        page: 1,
        page_len: 100000000,
        enterprise_id: 1
      },
      baseUrl,
      clientHeight: 0, // 屏幕的高度
      pickerOptions: this.banTime(), 

    }
  },
  created() {
    this.fetchData()
    this.clientHeight = `${document.documentElement.clientHeight}`;
  },
  methods: {
    // 限制月份
    banTime() {
      return {
        disabledDate(time) {
          const date = new Date()
          const year = date.getFullYear()
          let month = date.getMonth() + 1
          if (month >= 1 && month <= 9) {
            month = '0' + month
          }
          const currentdate = year.toString() + month.toString()
          const timeyear = time.getFullYear()
          let timemonth = time.getMonth() + 1
          if (timemonth >= 1 && timemonth <= 9) {
            timemonth = '0' + timemonth
          }
          const timedate = timeyear.toString() + timemonth.toString()
          return currentdate < timedate
        }
      }
    },
    // 获取列表
    fetchData(obj={}) {
      if(obj.page) {
        this.searchForm.page = obj.page
        this.searchForm.page_len = obj.page_len
      }
      this.listLoading = true
      this.firmList = []
      this.$http(listSupplierAccount(this.searchForm), (res) => {
        let firmList = res.data.result
        // 把合并项整理分开
        firmList.map((val, index) => {
          // 没有合并直接整理到数组中
          if(val.data_list.length==0) {
            let obj = Object.assign({}, val, {})
            delete obj.data_list
            obj.flag = true  // 记录是否在此项开始
            obj.sum = 1  // 一共多少项相同项(默认一项)
            this.firmList.push(obj)
          } else {
            for(let i=0;val.data_list.length>i;i++) {
              let obj = Object.assign({}, val, {})
              if(i==0) {
                obj.flag = true // 记录是否在此项开始
                obj.sum = obj.data_list.length // 一共多少项相同项
              }
              delete obj.data_list
              for(let item in val.data_list[i]) {
                obj[item] = val.data_list[i][item];
              }
              this.firmList.push(obj)
            }
          }
        })
        // 整理合计选项
        let sum = {
          flag: true, // 记录是否在此项开始
          sum: 1, // 一共多少项相同项
          supplier_id: '',
          supplier_num: "合计",
          supplier_name: '',
          order_ton: res.data.G_count,
          sum_fee: res.data.G_fee_sum,
          should_fee: res.data.G_should,
          already_pay: res.data.G_already_pay,
          owe_sum: res.data.G_owe_sum,
          init_pay: res.data.G_init_pay,
        }
        this.firmList[this.firmList.length] = sum
        this.total = res.data.data_sum
        this.listLoading = false
      })
    },
    // 整合同项
    objectSpanMethod({ row, column, rowIndex, columnIndex }) {
      if (columnIndex==0||columnIndex==1||columnIndex==7||columnIndex==8||columnIndex==9) {
        if (row.flag) {
          return {
            rowspan: row.sum,  // 由row.falg标志开始一共几项合并为一项
            colspan: 1
          };
        } else {
          return {
            rowspan: 0,
            colspan: 0
          };
        }
      }
    },
    // 配送产品
    getProductType(value) {
      return value=="type-00"?"散装":(value=="type-01"?"袋装":"")
    },
    // 导出
    handleDownload() {
      this.$http(exportSupplier(this.searchForm), (res) => {
        window.location.href = this.baseUrl + res.data.url
      })
    },
    // 付款明细
    goDetail(supplier_id) {
      this.$router.push({ path: '/financialManagement/supplier/payList',query:{supplier_id: supplier_id}})
    },
    // 结算运费
    handleType(supplier_id) {
      this.entryInfo.supplier_id = supplier_id
      this.dialogType = 'type'
      this.dialogEntry = true
    },
    // 
    getDraftType(value) {
      this.entryInfo.draft_type = value
    },
    // 保存结算运费
    submitForm() {
      this.$refs['postForm'].validate((valid) => {
        if (valid) {
          this.dialogType=='draft'?
          this.$http(saveDraft(this.entryInfo), res => {
            this.$message({
              message: '成功',
              type: 'success'
            })
            this.fetchData()
            this.dialogEntry = false
          }) : 
          this.$http(saveCash(this.entryInfo), res => {
            this.$message({
              message: '成功',
              type: 'success'
            })
            this.fetchData()
            this.dialogEntry = false
          })
        } else {
          return false
        }
      })
    },
    // 关闭弹窗
    closeDialog() {
      this.entryInfo = {}
      this.$refs['postForm'].resetFields();
    },
  }
}
</script>

<style lang='scss' scoped>

</style>