<template>
  <!-- 染损报表 -->
  <div id="dyeLossRateTable">
    <!-- 查询区域 -->
    <a-card :bordered="false">
      <div class="table-page-search-wrapper">
        <a-form layout="inline" @keyup.enter.native="searchQuery">
          <a-row :gutter="24">
            <a-col :md="6" :sm="8">
              <a-form-item label="订单号">
                <a-input placeholder="请输入订单号" v-model="queryParam.code"></a-input>
              </a-form-item>
            </a-col>

            <!-- <a-col :md="6" :sm="8">
              <a-form-item label="订单类型">
                <a-input placeholder="请输入订单类型" v-model="queryParam.orderType"></a-input> -->
            <!-- <a-select placeholder="请选择订单类型" v-model="queryParam.orderType">
                  <a-select-option :value="''">请选择</a-select-option>
                  <a-select-option :value="0">订单类型1</a-select-option>
                  <a-select-option :value="1">订单类型2</a-select-option>
                  <a-select-option :value="2">订单类型3</a-select-option>
                </a-select> -->
            <!-- </a-form-item>
            </a-col> -->

            <a-col :md="6" :sm="8">
              <a-form-item label="供应商">
                <a-input placeholder="请输入供应商" v-model="queryParam.venName"></a-input>
              </a-form-item>
            </a-col>

            <a-col :md="6" :sm="8">
              <a-form-item label="计划单号">
                <a-input placeholder="请输入计划单号" v-model="queryParam.planLotNumber"></a-input>
              </a-form-item>
            </a-col>

            <!-- <a-col :md="6" :sm="8">
                <a-form-item label="销售订单号">
                  <a-input placeholder="请输入销售订单号" v-model="queryParam.csocode"></a-input>
                </a-form-item>
              </a-col> -->
            <template v-if="toggleSearchStatus"> 
              <a-col :md="6" :sm="8">
              <a-form-item label="物料编码">
                <a-input placeholder="请输入物料编码" v-model="queryParam.cinvcode"></a-input>
              </a-form-item>
            </a-col>

            <a-col :md="6" :sm="8">
              <a-form-item label="颜色">
                <a-input placeholder="请输入颜色" v-model="queryParam.color"></a-input>
              </a-form-item>
            </a-col>
            </template>

            <a-col :md="6" :sm="8">
              <span style="float: left;overflow: hidden;" class="table-page-search-submitButtons">
                <a-button type="primary" @click="searchQuery" icon="search">查询</a-button>
                <a-button type="primary" @click="searchReset" icon="reload" style="margin-left: 8px">重置</a-button>
                <a @click="handleToggleSearch" style="margin-left: 8px">
                  {{ toggleSearchStatus ? '收起' : '展开' }}
                  <a-icon :type="toggleSearchStatus ? 'up' : 'down'" />
                </a>
              </span>
            </a-col>
          </a-row>
        </a-form>
      </div>
    </a-card>

    <!-- 导出 table-->
    <a-card :bordered="false" style="margin:10px 0;">
      <div class="table-operator">
        <a-button type="primary" icon="download" @click="handleExportXls('染损报表')">导出</a-button>
      </div>

      <!-- 子表合计 table rowKey="id" :scroll="{ x: 1500 }"   :pagination="ipagination"-->
      <div>
        <a-table
          bordered
          rowKey="index"
          v-if="dyeLossRateData"
          :columns="dyeLossRateColumns"
          :data-source="dyeLossRateData"
          :loading="loading"
          :pagination="pagination"
          @change="handleTableChange"
          ref="table"
          :footer="totalFooterShow"
        >
        </a-table>
      </div>
    </a-card>

    <!-- 引入 echarts -->
    <a-card :bordered="false">
      <div class="chart">
        <div class="someoneLossChart" v-if="queryParam.venName">
          <someoneLossChart ref="someoneLossChart" />
        </div>

        <div v-else class="allLossChart">
          <allLossChart />
        </div>
      </div>
    </a-card>
  </div>
</template>

<script>
import { JeecgListMixin } from '@/mixins/JeecgListMixin'
import JEllipsis from '@/components/jeecg/JEllipsis'
import moment from 'moment'
import { downFile } from '@/api/manage'

import allLossChart from '@views/reportForms/dye-loss-table/allLossChart.vue'
import someoneLossChart from '@views/reportForms/dye-loss-table/someoneLossChart'

import { dyeLossList } from '@api/reportForms/dye-loss-table.js'

export default {
  name: 'DyeLossRateTable', // 染损报表
  mixins: [JeecgListMixin],
  components: { JEllipsis, moment, allLossChart, someoneLossChart },

  data() {
    let ellipsis = (v, l = 20) => <j-ellipsis value={v} length={l} />
    return {
      // 表头
      dyeLossRateColumns: [
        {
          title: '序号',
          width: 50,
          dataIndex: 'index',
          key: 'index',
          customRender: (text, record, index) => `${index + 1}`,
          className: 'replacecolor'
        },
        {
          title: '物料编码',
          width: 100,
          dataIndex: 'cinvCode',
          className: 'replacecolor'
        },

        {
          title: '物料名称',
          width: 360,
          align: 'left',
          dataIndex: 'cinvName',
          className: 'replacecolor'
        },
        {
          title: '颜色',
          width: 180,
          dataIndex: 'color',
          align: 'left',
          customRender: t => ellipsis(t),
          className: 'replacecolor'
        },
        { title: '供应商', width: 180, dataIndex: 'cvenName', align: 'left', className: 'replacecolor' },
        {
          title: '订单号',
          width: 120,
          dataIndex: 'ccode',
          className: 'replacecolor'
        },
        { title: '订单数量', width: 90, dataIndex: 'iquantity', className: 'replacecolor' },
        { title: '采购入库数', width: 90, dataIndex: 'iquantity2', className: 'replacecolor' },
        { title: '材料出库数', width: 90, dataIndex: 'iquantity3', className: 'replacecolor' },
        { title: '核销数量', width: 90, dataIndex: 'imsquantity', className: 'replacecolor' },
        { title: '染损', width: 120, dataIndex: 'dyeLossRate', className: 'replacecolor' }
      ],
      dyeLossRateData: [], //染损数据
      loading: false, // 表格加载

      queryParam: {
        code: '', //订单号
        orderType: '', //订单类型
        cvenName: '', //供应商
        planLotNumber: '', //计划单号
        csocode: '', //销售订单号
        pageNo: '', //  点击的页数
        cinvcode: '', //物料编码
        color: '' //颜色
        //  pageSize: '3' //一页多少
      },
      // 分页
      pagination: {
        // total: '', //总条数
        // current: '', //当前页
        pageSize: '3' //一页多少
      },
      someoneChartData: {
        cvenNameArr: [], //供应商数组 chart
        cinvNameArr: [], //物料名称数组chart
        colorArr: [] //颜色数组chart
      }
    }
  },

  // html渲染出来后，操作dom
  mounted() {
    this.cancelLoading()
  },

  created() {
    this.getdyeLossList() //查询染损列表
  },

  methods: {
    cancelLoading() {
      setTimeout(() => {
        this.loading = false
      }, 500)
    },

    // 查询染损列表
    getdyeLossList() {
      this.$nextTick(() => {
        dyeLossList(this.queryParam).then(res => {
          if (res.success) {
            this.dyeLossRateData = res.result.records
            this.pagination = {
              total: res.result.total,
              current: res.result.current,
              pageSize: res.result.size
            }
            // console.log('染损列表', this.dyeLossRateData)
          }
        })
      })
    },
    // 查询按钮
    searchQuery() {
      if (this.queryParam.venName) {
        console.log('查询的是该供应商', this.queryParam.venName)
        console.log('应该调指定供应商接口,渲染chart')
        // 赋值给子组件作为接口参数
        this.$refs.someoneLossChart.venName = this.queryParam.venName
        console.log('[查询的供应商名称]', this.$refs.someoneLossChart.venName)
        this.$refs.someoneLossChart.getSomeoneLossData()
      }
      this.queryParam.pageNo = ''
      this.getdyeLossList() // 渲染染损列表
    },
    searchReset() {
      this.queryParam = {}
      this.getdyeLossList()
    },

    // 导出
    handleExportXls(fileName) {
      console.log('需导出的fileName:', fileName)
      const params = this.dyeLossRateData
      console.log('导出参数', params)
      downFile('/scas/dyeLoss/excel', params).then(data => {
        console.log('888')
        if (!data) {
          this.$message.warning('文件下载失败')
          return
        }
        if (typeof window.navigator.msSaveBlob !== 'undefined') {
          window.navigator.msSaveBlob(new Blob([data], { type: 'application/vnd.ms-excel' }), fileName + '.xls')
        } else {
          let url = window.URL.createObjectURL(new Blob([data], { type: 'application/vnd.ms-excel' }))
          let link = document.createElement('a')
          link.style.display = 'none'
          link.href = url
          link.setAttribute('download', fileName + '.xls')
          document.body.appendChild(link)
          link.click()
          document.body.removeChild(link) // 下载完成移除元素
          window.URL.revokeObjectURL(url) // 释放掉blob对象
        }
      })
    },
    // 合计行 TODO: table 单元格合并
    totalFooterShow(data) {
      if (data) {
        // console.log('需合计数据(合计行)data', data)
        return (
          <a-table
            rowKey={Math.random}
            bordered={false}
            pagination={false}
            columns={this.dyeLossRateColumns}
            dataSource={this.dyeLossRateDataSource || []}
            showHeader={false}
          ></a-table>
        )
      }
    },

    // 分页变化时触发
    handleTableChange(pagination, filters, sorter) {
      // console.log('分页器信息>>>>', pagination)
      if (Object.keys(sorter).length > 0) {
        this.isorter.column = sorter.field
        this.isorter.order = sorter.order == 'ascend' ? 'asc' : 'desc'
      }
      this.queryParam.pageNo = pagination.current
      this.getdyeLossList()
    }
  },
  computed: {
    // 合计数据
    dyeLossRateDataSource() {
      const summary = Object.assign({}, this.dyeLossRateData[1])
      for (const attr in summary) {
        summary[attr] = '合计'
      }
      let iQuantityNum = 0 //订单数量 合计
      this.dyeLossRateData.forEach(({ iquantity }) => {
        iQuantityNum = parseInt(iQuantityNum) + parseInt(iquantity)
      })
      summary['iquantity'] = iQuantityNum

      let iQuantity2Num = 0 //采购入库数 合计
      this.dyeLossRateData.forEach(({ iquantity2 }) => {
        iQuantity2Num = parseInt(iQuantity2Num) + parseInt(iquantity2)
      })
      summary['iquantity2'] = iQuantity2Num

      let iQuantity3Num = 0 //材料出库数 合计
      this.dyeLossRateData.forEach(({ iquantity3 }) => {
        iQuantity3Num = parseInt(iQuantity3Num) + parseInt(iquantity3)
      })
      summary['iquantity3'] = iQuantity3Num

      let iMSQuantityNum = 0 //核销数量 合计
      this.dyeLossRateData.forEach(({ imsquantity }) => {
        iMSQuantityNum = parseInt(iMSQuantityNum) + parseInt(imsquantity)
      })
      summary['imsquantity'] = iMSQuantityNum

      let dyeLossRateNum = 0 //染损合计
      this.dyeLossRateData.forEach(({ dyeLossRate }) => {
        dyeLossRateNum = parseInt(dyeLossRateNum) + parseInt(dyeLossRate)
      })
      summary['dyeLossRate'] = dyeLossRateNum

      return [summary]
    }
  }
}
</script>
<style lang="less" scoped>
@import '~@assets/less/common.less';
@import '~@assets/less/overwriter.less';
/deep/ .ant-table-thead > tr > th {
  text-align: center;
  // font-weight: 700;
}

/deep/ .ant-table-tbody {
  text-align: center;
}

// /deep/ th.replacecolor {
//   background-color: #ccc;
// }

/deep/ .ant-table-footer .ant-table.body {
  // overflow: hidden !important;
}
/deep/ .ant-table.ant-table-bordered .ant-table-footer {
  border: none;
  padding: 0;
}
.allLossChart,
.someoneLossChart {
  height: 600px;
  text-align: center;
  padding-top: 10px;
}
</style>
