<template>
  <div class="reconciliation">
    <y-table-pro
      ref="table"
      has-loading
      ui-style="antd"
      auto-adaptive-height
      :load-data-api="loadData"
      :columns="columns"
      label-suffix="："
      :params.sync="params"
      :page-size="10"
      offset="90"
      :is-vxe="true"
      :before-check-all="beforeCheckAll"
      :has-batch-button="true"
      :show-overflow="true"
      :tooltip-config="tableTooltipConfig"
      :tree-config="{
        transform: false,
        rowField: 'id',
        parentField: 'partnerId',
        children: 'childrenList',
        reserve:true
      }"
      label-width="110px"
      :default-expand-all="true"
      :column-config="{ resizable: true }"
      :row-config="{ height: 100, isCurrent: true, isHover: true }"
      :checkbox-config="{ reserve:true,labelField: 'id', highlight: true , checkStrictly: true }"
      :default-params="{ billType: 'PROCUREMENT', size: 10 }"
      show-util-bar
      show-select-all
      :show-select-all-count="false"
      border
      :style="{paddingBottom:'20px'}"
      @select-all-page="handleSelectAllPage"
      @loaded="handleLoaded"
      @select-all="handleToggleSelectAll"
      @select="handleSelection"
    >
      <div slot="table">
        <el-button @click="handleExport">导出对账单</el-button>
      </div>
      <div slot="action-right">
        <el-button
          class="action-right"
          type="primary"
          :loading="loading"
          @click="hanleSure"
        >确认账单</el-button>
      </div>
    </y-table-pro>
  </div>
</template>
<script>

const findComponentForward = function(context, componentName) {
  let target = null // 目标组件
  const name = context.$options.name
  if (name === componentName) {
    target = context
  }
  if (target) {
    return target
  } else {
    // 获取当前上下文所有子组件
    const children = context.$children
    // 编历子组件
    for (const child of children) {
      target = findComponentForward(child, componentName)
      if (target) return target
    }
  }
  return target
}

import { filter } from 'lodash'
import api from './api'
export default {
  components: {
  },
  data() {
    return {
      tableTooltipConfig: {
        showAll: false,
        enterable: true,
        leaveDelay: 1000
      },
      // 账单类型
      typeList: [
        { label: '入库账单', value: 'PROCUREMENT_WAREHOUSE_IN' },
        { label: '退货账单', value: 'PROCUREMENT_STOCK_REFUND' },
        { label: '不结算商品调整账单', value: 'PROCUREMENT_ORDER_ADJUST' },
        { label: '不结算商品退货调整账单', value: 'PROCUREMENT_ORDER_ADJUST_BACK' },
        { label: '调价账单', value: 'PROCUREMENT_ORDER_ADJUST_PRICE' }
      ],
      selection: [],
      loading: false, // 确认账单
      statusType: [
        { label: '待确认', value: 'CONFIRM' },
        { label: '部分确认', value: 'CONFIRM_PART' },
        { label: '已确认', value: 'CONFIRMED' },
        { label: '部分开票', value: 'INVOICE_PART' },
        { label: '已开票', value: 'INVOICEED' }
      ],
      logList: [], // 操作记录list
      columns: [
        {
          type: 'selection',
          width: '100',
          treeNode: true,
          // 待对账，可以勾选
          selectable: (row) => {
            return !!row.row?.status
            // console.log(row.row?.status)
            // let flag = false
            // if (row.row?.status === 'CONFIRMED' || row.row?.status === 'INVOICE_PART' || row.row?.status === 'INVOICEED') {
            //   flag = true
            // }
            // return !flag
          }
        },

        {
          prop: 'code',
          label: '账单编号'
        },
        {
          prop: 'originServiceCode',
          label: '单据编号',
          filter: true,
          hidden: false,
          fieldType: 'Input',
          placeholder: '请输入搜索',
          render: (h, { row }) => {
            return <div>
              <div>{row.originServiceCode}</div>
              {row.subServiceCode ? <div>原单：{row.subServiceCode}</div> : ''}
            </div>
          }
        }
        // {
        //   prop: 'code',
        //   label: '账单编号',
        //   filter: true,
        //   hidden: true,
        //   fieldType: 'Input',
        //   placeholder: '请输入搜索'
        // },
        // {
        //   prop: 'billSubject',
        //   label: '对账主体',
        //   render: (h, { row }) => {
        //     return <div>
        //       <div>{row.billSubject}</div>
        //       <div style={'marginTop:20px '}>税号：{row.dutyParagraph}</div>
        //     </div>
        //   }
        // },
        // {
        //   prop: 'type',
        //   label: '账单类型',
        //   filter: true,
        //   hidden: false,
        //   remote: false,
        //   fieldType: 'Select',
        //   options: [
        //     { label: '入库账单', value: 'PROCUREMENT_WAREHOUSE_IN' },
        //     { label: '退货账单', value: 'PROCUREMENT_STOCK_REFUND' },
        //     { label: '不结算商品调整账单', value: 'PROCUREMENT_ORDER_ADJUST' },
        //     { label: '不结算商品退货调整账单', value: 'PROCUREMENT_ORDER_ADJUST_BACK' },
        //     { label: '调价账单', value: 'PROCUREMENT_ORDER_ADJUST_PRICE' }
        //   ],
        //   render: (h, { row }) => {
        //     return <div> {this.getLabelValue(this.typeList, row.type)}</div>
        //   }
        // },
        // {
        //   prop: 'status',
        //   label: '账单状态',
        //   filter: true,
        //   hidden: false,
        //   remote: false,
        //   fieldType: 'Select',
        //   options: [
        //     { label: '待确认', value: 'CONFIRM' },
        //     { label: '部分确认', value: 'CONFIRM_PART' },
        //     { label: '已确认', value: 'CONFIRMED' },
        //     { label: '部分开票', value: 'INVOICE_PART' },
        //     { label: '已开票', value: 'INVOICEED' }
        //   ],
        //   render: (h, { row }) => {
        //     return (
        //       <el-button
        //         type='text'
        //         onClick={() => {
        //           this.stutasPopup(row)
        //         }}
        //       >
        //         {this.getLabelValue(this.statusType, row.status)}
        //       </el-button>
        //     )
        //   }
        // },
        // {
        //   prop: 'totalPriceIncludingTax',
        //   label: '账单金额',
        //   render: (h, { row }) => {
        //     return (
        //       <div>
        //         <div>含税总金额：{row.totalPriceIncludingTax}</div>
        //         <div>税额总金额： {row.totalTaxAmount}</div>
        //         <div>不含税总金额： {row.totalPriceExcludingTax}</div>
        //       </div>
        //     )
        //   },
        //   width: '200'
        // },
        // {
        //   prop: 'createTime',
        //   label: '账单时间',
        //   filter: true,
        //   hidden: true,
        //   excessive: true,
        //   fieldType: 'DatePicker',
        //   type: 'daterange',
        //   rangeSeparator: '至',
        //   startPlaceholder: '开始日期',
        //   endPlaceholder: '结束日期',
        //   clearable: true,
        //   placeholder: '请选择日期范围',
        //   onPick: (value) => {
        //     if (value) {
        //       const startDate = value?.[0]
        //       const endDate = value?.[1]
        //       this.params.beginTime = startDate && formatDate(startDate, 'yyyy-MM-DD')
        //       this.params.endTime = endDate && formatDate(endDate, 'yyyy-MM-DD')
        //     } else {
        //       this.params.beginTime = null
        //       this.params.endTime = null
        //     }
        //   }
        // },
        // {
        //   prop: 'createTime',
        //   label: '账单时间'
        // },
        // {
        //   prop: 'warehouseInTime',
        //   label: '业务完成时间'
        // },
        // {
        //   prop: 'expectReceivingTime',
        //   label: '要求到店日期',
        //   filter: true,
        //   excessive: true,
        //   fieldType: 'DatePicker',
        //   type: 'daterange',
        //   rangeSeparator: '至',
        //   startPlaceholder: '开始日期',
        //   endPlaceholder: '结束日期',
        //   clearable: true,
        //   placeholder: '请选择日期范围',
        //   formatter: val => {
        //     return formatDate(val.expectReceivingTime, 'yyyy-MM-DD')
        //   },
        //   renderLabel: (h, { row, col }) => {
        //     return <div>
        //       要求到店日期 <y-tips
        //         icon='iconwenhao-xianxingyuankuang'
        //         origin='iconfont'
        //         effect='dark'
        //         placement='right'
        //       >
        //       只查询不结算商品账单
        //       </y-tips>:
        //     </div>
        //   },
        //   onPick: (value) => {
        //     const startDate = value?.[0]
        //     const endDate = value?.[1]
        //     console.log(startDate, endDate)
        //     this.params.expectReceivingTimeStart = startDate ? formatDate(startDate, 'yyyy-MM-DD') : null
        //     this.params.expectReceivingTimeEnd = endDate ? formatDate(endDate, 'yyyy-MM-DD') : null
        //     console.log(this.params.expectReceivingTimeStart, this.params.expectReceivingTimeEnd)
        //   }
        // },
        // {
        //   prop: 'billSubject',
        //   label: '对账主体',
        //   filter: true,
        //   hidden: true,
        //   fieldType: 'Input',
        //   placeholder: '请输入搜索'
        // },
        // {
        //   label: '操作',
        //   render: (h, { row, index }) => {
        //     return (
        //       <div>
        //         <el-button
        //           type='text'
        //           onClick={() => {
        //             this.goDetail(row)
        //           }}
        //         >
        //           详情
        //         </el-button>
        //       </div>
        //     )
        //   }
        // }
      ],
      params: {
        size: 10,
        selectAll: 0
      }
    }
  },
  async created() {},
  methods: {
    async loadData(args) {
      return await api.productApi.getSkuPackage(args)
    },
    goDetail(row) {
      this.$router.push({
        path: '/settlement-center/supplier-detail',
        query: {
          id: row.id,
          code: row.code,
          originServiceCode: row.originServiceCode
        }
      })
    },
    handleToggleSelectAll(val) {
      this.selection = val
    },
    async hanleSure() {

    },
    handleSelectAllPage(val) {
      this.params.selectAll = val
    },
    beforeCheckAll(callback) {
      const selection = this.loadTableData
      if (selection.length) {
        const filterFn = (tableData) => {
          const status = 'CONFIRM' // 待对账
          return filter(tableData, { status })
        }
        callback(true, filterFn)
      }
    },
    setDefaultValue(defaultParams) {
      Object.keys(defaultParams).forEach((key) => {
        if (defaultParams[key] === '') {
          // 如果值为空字符串，将默认值改为null
          defaultParams[key] = null
        }
      })
      return defaultParams
    },
    async handleExport() {
    },
    handleLoaded(res) {
      this.loadTableData = res.data.records
      const table = findComponentForward(this, 'VTable')
      this.$nextTick(() => table.setAllTreeExpand(true))
    },
    getLabelValue(options, value) {
      const res = options.find((v) => v.value === value)
      return res ? res.label : '其他'
    },
    handleSelection(selection, row) {
      const { childrenList } = row
      if (childrenList.length) {
        const table = findComponentForward(this, 'VTable')
        const rowIndex = selection.findIndex(item => item.id === row.id)
        if (rowIndex >= 0) {
          table.setCheckboxRow(childrenList, true)
          this.$nextTick(() => {
            let selection = table.getCheckboxRecords()
            const reserveSelection = table.getCheckboxReserveRecords()
            selection = selection.concat(reserveSelection)
            this.selection = selection
          })
        }
      } else {
        this.selection = selection
      }
    },
    async getWarehouseOptions() {

    }
  }
}
</script>
<style lang="scss" scoped>
.reconciliation {
  height: calc(100vh - 190px) !important;
  overflow-y: scroll;
  .action-right{
    margin-left: 20px;
  }
}
</style>
