<template>
  <el-drawer
    v-loading="DrawerLoading"
    v-if="drawer"
    :visible="true"
    :close-on-press-escape="false"
    :wrapperClosable="false"
    :with-header="false"
    :modal="false"
    size="100%"
  >
    <div class="drawer-heder">
      <div class="heder-left">
        <div class="header-text">
          <span>{{ propsData[title[0].prop] }}</span>
          <span>{{ title[0].label }}</span>
        </div>
      </div>
      <div class="heder-right">
        <curren-Button
          :Butttondata="Butttondata"
          @tableButtonClick="tableButtonClick"
        >
          <template>
            <el-dropdown
              trigger="click"
              @command="handleCommand"
              v-if="JSON.stringify(dropdownData) != '{}'"
            >
              <el-button size="mini" icon="el-icon-more"></el-button>
              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item
                  v-for="(item, index) in dropdownData"
                  :key="index"
                  :command="item.command"
                  >{{ item.label }}</el-dropdown-item
                >
              </el-dropdown-menu>
            </el-dropdown>
          </template>
        </curren-Button>
      </div>
    </div>
    <div class="drawer-main">
      <curren-tabs
        :tabsData="dropdownTabs"
        :activeName="firstTabs"
        type="border-card"
        @handleClick="handleClick"
      >
        <template slot-scope="scope">
          <curren-descriptions
            border
            v-if="scope.value == 'xq'"
            :column="column"
            :direction="direction"
            :colon="false"
            :tabsDesTions="tabsDesTions"
            :propsData="propsData"
          >
          </curren-descriptions>
          <!-- 明细 包含分页 头部按钮等 -->
          <tablePagination
            v-if="scope.value == 'mx'"
            :currenButtonData="detailHeaderButton"
            :tableData="propsData.details"
            :tableColumns="tableColumns"
            :setUTableHeight="showDetailColumnsSet && showDetailFilters ? 300 : 260"
            @rowDrop="rowDrop"
            :searchOverallCoverHeight="'calc(100vh - 345px)'"
            :rowSource="'detail_api'"
            :rowMaxHeight="rowMaxHeight"
            :totalCount="totalCountForDetail"
            :MaxResultCount="MaxResultCount"
            @sortChange="sortChangeForDetail"
            @alertoldSkipCount="alertoldSkipCountForDetail"
            @alterResultCount="alterResultCountForDetail"
            @handleSelectionChange="handleSelectionChange"
            :currentPageProps="oldSkipCount"
            @overallSearchFormClick="overallSearchClickForDetail"
            :httpOverallSearchData="httpOverallSearchData"
            @buttonOperationClick_left="buttonOperationClick_left"
            :buttonOperationList_left="buttonOperationList_left"
            :tableLoading="Loading.tableLoading"
          ></tablePagination>
          <!-- 新增汇总 表头 区分明细表头使用 summaryTableColumns -->
          <umyTable
            v-if="scope.value == 'hz'"
            :tableBorder="true"
            :tableData="propsData.summaryDetails"
            :tableColumns="summaryTableColumns.length == 0 ? tableColumns : summaryTableColumns"
            :selectionTable="selectionTable"
            :requiredRules="false"
            @sortChange="sortChange"
            @handleSelectionChange="handleSelectionChange"
            @inlineDialog="inlineDialog"
            @buttonClick="buttonClick"
            :setUTableHeight="210"
          >
            <template>
              <slot></slot>
            </template>		
          </umyTable>
          <!-- 自定义扩展 -->
          <umyTable
            v-if="
              scope.value == zdyValue && 
              scope.value != 'xq' &&
              scope.value != 'mx' && 
              scope.value != 'hz' &&
              scope.value != 'zwlcj'
            "
            :tableBorder="true"
            :tableLoading="tableLoading"
            :tableData="otherData"
            :tableColumns="zdyTableColumns"
            :selectionTable="selectionTable"
            :requiredRules="false"
            @sortChange="sortChange"
            @handleSelectionChange="handleSelectionChange"
            @inlineDialog="inlineDialog"
            @buttonClick="buttonClick"
            :setUTableHeight="210"
          >
            <template>
              <slot></slot>
            </template>		
          </umyTable>
        </template>
      </curren-tabs>
    </div>
    <div class="drawer-Shut" @click="drawerShut">
      <el-button type="danger" size="mini">关闭</el-button>
    </div>
    <!-- 明细-查看详情 -->
    <el-dialog 
      width="90%"
      :modal-append-to-body="false"
      :append-to-body="false"
      :title="detailInfoTitle" 
      :visible.sync="displayDialog.detailInfoDialog"
      :show-close="true"
    >
      <div>
          <curren-descriptions
              v-if="detailInfoTableData"
              border
              :column="column"
              :direction="direction"
              :colon="false"
              :tabsDesTions="tableColumns"
              :propsData="detailInfoTableData"
              style="padding-bottom: 20px;"
          ></curren-descriptions>
      </div>
    </el-dialog>
  </el-drawer>
</template>
<script>
import { getListByItemcode,byItem,byProduct,byComponent,bySupplierCode,byLocation,byLocationCode,
  relationByLocationCode,byComponentCJ,purRecNoteCustomInfo,getPageListForDetail 
} from "@/api/wms-api"
import searchOverall from "@/components/searchOverall"
import currenButton from "@/components/currenButton"
import currenDescriptions from "@/components/currenDescriptions"
import currenTabs from "@/components/currenTabs"
import currenTable from "@/components/currenTable"
import pagination from "@/components/Pagination"
import rowDrop from "@/components/rowDrop/index.vue"
import * as allUrlOption from '@/utils/baseData/urlOption'
import { LoadingMixins } from "@/mixins/LoadingMixins";
export default {
  name: 'currenTabel-drawer',
  components: {
    pagination,
    currenButton,
    currenDescriptions,
    currenTabs,
    currenTable,
    searchOverall,
    rowDrop
  },
  mixins: [
    LoadingMixins,
  ],
  props: {
    rowMaxHeight:{
      type:String,
      default:'calc(90vh - 450px)'
    },
    // 操作列按钮
    buttonOperationList_left:{
      type: Array,
      default: null,
    },
    // 是否显示明细-字段设置
    showDetailColumnsSet:{
      type: Boolean,
      default: true
    },
    // 是否显示明细-筛选
    showDetailFilters:{
      type: Boolean,
      default: true
    },
    title: {
      type: Array,
      default: () => {
        return []
      }
    },
    DrawerLoading: {
      type: Boolean,
      default: true
    },
    drawer: {
      type: Boolean,
      default: false
    },
    dropdownData: {
      type: Object,
      default: () => {
        return {}
      }
    },
    propsData: {
      type: Object,
      default: () => {
        return {}
      }
    },
    tabsDesTions: {
      type: Array,
      default: () => {
        return []
      }
    },
    dropdownTabsData: {
      type: Array,
      default: () => {
        return []
      }
    },
    tableLoading: {
      type: Boolean,
      default: false
    },
    tableColumns: {
      type: Array,
      default: () => {
        return []
      }
    },
    summaryTableColumns: {
      type: Array,
      default: () => {
        return []
      }
    },
    Butttondata: {
      type: Array,
      default: () => {
        return [{
          type: 'warning',
          icon: 'el-icon-edit',
          label: '编辑',
          name: 'edit',
          size: 'mini'
        }]
      }
    },
    selectionTable: {
      type: Boolean,
      default: false
    },
    MaxResultCount: {
      type: Number,
      default: 0
    },
    totalCount: {
      type: Number,
      default: 0
    },
    currentPage: {
      type: Number,
      default: 0
    },
    // 详情展现列数，默认为2列展现
    column: {
      type: Number,
      default: 2
    },
    // 详情展示方式，默认水平分布
    direction: {
      type: String,
      default: 'horizontal'
    },
    // 详情tabs排序默认
    firstTabs: {
      type: String,
      default: 'xq'
    }

  },
  computed: {
    dropdownTabs () {
      // 带有特殊扩展tabs页的
      if (this.dropdownTabsData.length !== 0) {
        return this.dropdownTabsData
      } else {
        // 正常普通 详情，明细，汇总
        // if (Object.keys(this.propsData).length != 0) {
        if (Object.keys(this.propsData)) {
          this.initDropdownTabsData = [{
            label: "详情",
            name: 'xq'
          }]
          // 明细可以为空数组，前端分页使用
          if(this.propsData.details){
            this.initDropdownTabsData.push({
              label: "明细",
              name: 'mx'
            })
          }
          if(this.propsData.summaryDetails && this.propsData.summaryDetails.length > 0){
            this.initDropdownTabsData.push({
              label: "汇总",
              name: 'hz'
            })
          }
        }
        return this.initDropdownTabsData
      }
    },
  },
  mounted () {
    this.initDetailHeaderButton()
  },
  data () {
    return {
      detailHeaderButton:null,//明细-上方按钮
      detailInfoTableData:null,//明细-查看详情弹窗数据
      detailInfoTitle:null,//明细-查看详情弹窗title
      otherData:[], // 切换tabs页赋值
      zdyTableColumns:[], // 自定义表头
      zdyValue:'', // 自定义展现值
      // firstTabs:'xq',
      initDropdownTabsData:[
        {
          label: "详情",
          name: 'xq'
        },
        {
          label: "明细",
          name: 'mx'
        },
        {
          label: "汇总",
          name: 'hz'
        }
      ],
      //明细列表- 改变当前页
      oldSkipCount: 1,
      // 明细列表- 全面搜索：当前列表数据请求接口的筛选条件
      httpOverallSearchData:null,
      //明细列表- 分页参数
      PageListParams: {
        condition: {
          filters: []
        },
        Sorting: "",
        SkipCount: 0,
        MaxResultCount: 20,
      },
      totalCountForDetail:0,
      //明细-查看主表的连接id
      URLOption_masterId:allUrlOption[this.$route.name].masterId || 'masterId',
      //明细-列表
      URLOption_detailList:allUrlOption[this.$route.name].detailListURL,
    }
  },
  methods: {
    // 明细列表 - 获取明细列表（后端分页）
    getDetailList(data,successFn,errorFn){
      if(data)this.PageListParams.condition.filters = []
      // 获取明细分页信息
      let _hasId = false
      this.PageListParams.condition.filters.forEach(item=>{
        if(item.column == this.URLOption_masterId){
          _hasId = true
        }
      })
      if(!_hasId || data){
        this.PageListParams.condition.filters.push({
          logic: "And",
          column: this.URLOption_masterId,
          action: "==",
          value: data ? data.id : this.propsData.id
        })
      }
      this.PageListParams.SkipCount = (this.oldSkipCount - 1) * this.PageListParams.MaxResultCount
      this.Loading.tableLoading = true
      getPageListForDetail(this.PageListParams,this.URLOption_detailList)
        .then(result => {
          this.propsData.details = result.items
          this.totalCountForDetail = result.totalCount
          this.Loading.tableLoading = false
          if(successFn)successFn()
        })
        .catch(err => {
          this.Loading.tableLoading = false
          if(errorFn)errorFn()
          this.$message.error("数据获取失败")
        })
    },
    // 明细列表 - 全面筛选组件查询
    overallSearchForDetailHandle(options){
      let _data_primary = options.data_primary,
          _data_moreList = options.data_moreList,
          _option_primary = options.option_primary,
          _vm_quickly = options.vm_quickly,
          _vm_moreList = options.vm_moreList

      //普通筛选数据集合
      let _primary_filters = []
      _option_primary.forEach(item=>{
        if(_data_primary[item.prop] && String(_data_primary[item.prop]).length > 0){
          let _item = {
            action:item.action || '==',
            column:item.prop,
            logic:'And',
            value:String(_data_primary[item.prop])
          }
          _primary_filters.push(_item)
        }
      })
      //高级筛选数据集合
      let _moreList_filters = []
      _data_moreList.filters.forEach(item=>{
        if(String(item.column).length > 0 && String(item.value).length > 0){
          _moreList_filters.push(item)
        }
      })
      // 全部筛选数据集合
      let _all_filters = []
      _all_filters = _primary_filters.concat(_moreList_filters)
      // 调用接口数据配置
      this.oldSkipCount = 1
      this.Loading.tableLoading = true;
      this.PageListParams.SkipCount = (this.oldSkipCount - 1) * this.PageListParams.MaxResultCount;
      this.PageListParams.condition = {filters:_all_filters}
      this.getDetailList(null,()=>{
        //快速搜索清空
        if(_vm_quickly){_vm_quickly.searchNormalClear(true)}
        //关闭高级筛选
        if(_vm_moreList){_vm_moreList.changeMoreListShow(false)}
        // 同步当前列表数据请求接口的筛选条件
        this.httpOverallSearchData = {}
        this.httpOverallSearchData.params = JSON.parse(JSON.stringify(_data_primary))
        this.httpOverallSearchData.moreList = JSON.parse(JSON.stringify(_data_moreList))
      },()=>{
        //快速搜索清空
        if(_vm_quickly){_vm_quickly.searchNormalClear(true)}
        //关闭高级筛选
        if(_vm_moreList){_vm_moreList.changeMoreListShow(false)}
      })
    },
    // 明细列表 - 全面筛选所有按钮操作集
    overallSearchClickForDetail(options){
      let _item = options.item;
      // 普通搜索 + 高级搜索 + 普通重置 + 高级重置
      if(
        _item.name == 'search' || _item.name == 'moreList-search' ||
        _item.name == 'reset' || _item.name == 'moreList-reset'
      ){
        this.overallSearchForDetailHandle(options)
      }
    },
    // 明细列表 -接收分页组件emit改变当前页
    alertoldSkipCountForDetail(val) {
      this.oldSkipCount = val;
      this.getDetailList();
    },
    // 明细列表 -接收分页组件emit改变每页最大页数
    alterResultCountForDetail(val) {
      this.PageListParams.MaxResultCount = val;
      this.getDetailList();
    },
    // 明细列表 - 排序查询
    sortChangeForDetail(val) {
      const {
        prop,
        order
      } = val;
      if (!prop || !order) {
        this.PageListParams.Sorting = "";
        this.oldSkipCount = 1;
        this.getDetailList();
        return;
      }
      let orderdata = order.substr(0, order.indexOf("c") + 1);
      const props = prop.charAt(0).toUpperCase() + prop.slice(1)
      this.PageListParams.Sorting = props + " " + orderdata.toUpperCase();
      this.oldSkipCount = 1;
      this.getDetailList();
    },
    // 初始化明细-上方按钮
    initDetailHeaderButton(){
      this.detailHeaderButton = []
      if(this.showDetailColumnsSet){this.detailHeaderButton.push(this.defaultFieldSettingBtn())}
      if(this.showDetailFilters){this.detailHeaderButton.push(this.defaultFilterBtn())}
    },
    // 关闭明细-详情弹窗
    closeDetailInfo(val){
      this.displayDialog.detailInfoDialog = val || false
    },
    // 明细-操作列事件
    buttonOperationClick_left(row, item, index){
      // 查看详情
      if(item.name == "info"){
        this.displayDialog.detailInfoDialog = true
        this.detailInfoTableData = row
        let _name = allUrlOption[this.$route.name].detailInfoName
        this.detailInfoTitle = _name ? row[_name] + ' 详情' : '详情'
      }
      this.$emit('buttonOperationClick_left',row, item, index)
    },
    rowDrop(data,type) {
      this.$emit('rowDrop',data,type)
    },
    handleCommand (command) {
      this.$emit('handleCommand', command)
    },
    drawerShut () {
      this.closeDetailInfo(false)
      this.$emit('drawerShut', false)
    },
    tableButtonClick (val) {
      this.$emit('drawerbutton', val)
    },
    //排序
    sortChange (data) {
      this.$emit('sortChange', data)
    },
    //点击selection框
    handleSelectionChange (val) {
      this.$emit("handleSelectionChange", val)
    },
    //点击name提交emit打开编辑页面
    inlineDialog (row) {
      this.$emit("inlineDialog", row)
    },
     //接收分页组件emit改变每页最大页数
    alterResultCountDetails (val) {
      this.$emit('alterResultCountDetails', val)
    },
    //接收分页组件emit改变当前页
    alertoldSkipCountDetails (val) {
      this.$emit('alertoldSkipCountDetails', val)
    },
    buttonClick(row) {
      this.$emit("buttonClick", row);
    },
    // tabs 切换页
    handleClick (val) {
      this.$emit("currenTabsChange", val);//父级获取当前的tab内容
      this.zdyValue = val.name
      this.dropdownTabsData.forEach( item => {
        if (item.name == val.name) {
          let parent = this.$parent
          parent.tableLoading = true
          // 详情 明细 汇总
          parent.firstTabs = val.name
          if (val.name == 'xq' || val.name == 'mx' || val.name == 'hz') {
            this.zdyTableColumns = []
            this.otherData = []
            parent.tableLoading = false
          } else {
            this.zdyTableColumns = []
            this.otherData = []
            // this.firstTabs = val.name
          // 其他自定义tab页
            if (item.functionName == 'getListByItemcode') {
              let params = {
                itemCode: this.propsData.code
              }
              getListByItemcode(params, item.url).then(res => {
                let zdyTableColumnsJSON = JSON.parse(JSON.stringify(this.$isTableColumns[item.tableColumns]));
                delete zdyTableColumnsJSON[0].type
                this.zdyTableColumns = zdyTableColumnsJSON
                this.otherData = res
                parent.tableLoading = false
              }).catch(err => {
                console.log(err)
                parent.tableLoading = false
              })
            }
            else if(item.functionName == "customerDismantleBackFlushNote"){
              let zdyTableColumnsJSON = JSON.parse(JSON.stringify(this.$isTableColumns[item.tableColumns]));
              delete zdyTableColumnsJSON[0].type
              this.zdyTableColumns = zdyTableColumnsJSON
              this.otherData = this.propsData.noteAndBackFlushDetails
            }
          }
        }
      })
    },
    // 递归 子级层级
    recursion(val){
      val.forEach(item => {
        if(item.componentDTOs) {
          item.children = item.componentDTOs
          this.recursion(item.componentDTOs)
        }
      })
    }
  }
}
</script>
<style lang="scss" scoped>
// el-drawer
@import "./style/index.scss";
</style>