<template>
  <a-card :bordered="false">
    <div ref="pie" :style="{ 
        width: '600px', 
        height: '400px', 
        position: 'absolute', 
        left: '-9999px',
        top: '-9999px',
        visibility: 'hidden'
      }" />
    <div ref="barline" :style="{ 
        width: '600px', 
        height: '400px', 
        position: 'absolute', 
        left: '-9999px',
        top: '-9999px',
        visibility: 'hidden'
      }" />
    <!-- 查询区域 -->
    <div class="table-page-search-wrapper">
      <a-form layout="inline" @keyup.enter.native="searchQuery">
        <a-row :gutter="24">
        </a-row>
      </a-form>
    </div>
    <!-- 查询区域-END -->

    <!-- 操作按钮区域 -->
    <div class="table-operator">
      <a-button @click="handleAdd" type="primary" icon="plus">新增</a-button>
      <!-- <a-button type="primary" icon="download" @click="handleExportXls('生产计划')">导出</a-button> -->
      <!-- <a-upload name="file" :showUploadList="false" :multiple="false" :headers="tokenHeader" :action="importExcelUrl" @change="handleImportExcel" :customRequest="customRequest">
        <a-button type="primary" icon="import">导入</a-button>
      </a-upload> -->
      <!-- 高级查询区域 -->
      <!-- <j-super-query :fieldList="superFieldList" ref="superQueryModal" @handleSuperQuery="handleSuperQuery"></j-super-query>
      <a-dropdown v-if="selectedRowKeys.length > 0">
        <a-menu slot="overlay">
          <a-menu-item key="1" @click="batchDel"><a-icon type="delete"/>删除</a-menu-item>
        </a-menu>
        <a-button style="margin-left: 8px"> 批量操作 <a-icon type="down" /></a-button>
      </a-dropdown> -->
    </div>

    <!-- table区域-begin -->
    <div>
      <div class="ant-alert ant-alert-info" style="margin-bottom: 16px;">
        <i class="anticon anticon-info-circle ant-alert-icon"></i> 已选择 <a style="font-weight: 600">{{ selectedRowKeys.length }}</a>项
        <a style="margin-left: 24px" @click="onClearSelected">清空</a>
      </div>

      <a-table
        ref="table"
        size="middle"
        :scroll="{x:true}"
        bordered
        rowKey="id"
        :columns="columns"
        :dataSource="dataSource"
        :pagination="ipagination"
        :loading="loading"
        :rowSelection="{selectedRowKeys: selectedRowKeys, onChange: onSelectChange}"
        class="j-table-force-nowrap"
        @change="handleTableChange">

        <template slot="htmlSlot" slot-scope="text">
          <div v-html="text"></div>
        </template>
        <template slot="imgSlot" slot-scope="text,record">
          <span v-if="!text" style="font-size: 12px;font-style: italic;">无图片</span>
          <img v-else :src="getImgView(text)" :preview="record.id" height="25px" alt="" style="max-width:80px;font-size: 12px;font-style: italic;"/>
        </template>
        <template slot="fileSlot" slot-scope="text">
          <span v-if="!text" style="font-size: 12px;font-style: italic;">无文件</span>
          <a-button
            v-else
            :ghost="true"
            type="primary"
            icon="download"
            size="small"
            @click="downloadFile(text)">
            下载
            <span v-if="text" style="color: #13CE66;">（{{text ? "已解析" : "未解析"}}）</span>
            <span v-else style="color: #E6A23C;">（{{text ? "已解析" : "未解析"}}）</span>
          </a-button>


        </template>

        <span slot="action" slot-scope="text, record">
          <a @click="handleEdit(record)">编辑</a>

          <a-divider type="vertical" />
          <a @click="handleDetail(record)">详情</a>

          <a-divider type="vertical" />
          <a-popconfirm title="确定删除吗?" @confirm="() => handleDelete(record.id)">
            <a>删除</a>
          </a-popconfirm>

          <a-divider type="vertical" />
          <a @click="handleAnalysis(record.id)">解析</a>

          <a-divider type="vertical" />
          <a @click="handleReport(record.id)">生成报告</a>

          <a-divider type="vertical" />
          <a @click="handleEmal(record.id)">发送邮件</a>
        </span>

      </a-table>
    </div>

    <prod-plan-modal ref="modalForm" @ok="modalFormOk"></prod-plan-modal>
  </a-card>
</template>

<script>

  import '@/assets/less/TableExpand.less'
  import { mixinDevice } from '@/utils/mixin'
  import { JeecgListMixin } from '@/mixins/JeecgListMixin'
  import ProdPlanModal from './modules/ProdPlanModal'
  import {  getAction,downFile,postAction} from '@/api/manage'

  export default {
    name: 'ProdPlanList',
    mixins:[JeecgListMixin, mixinDevice],
    components: {
      ProdPlanModal
    },
    data () {
      return {
        description: '生产计划管理页面',
        // 表头
        columns: [
          {
            title: '#',
            dataIndex: '',
            key:'rowIndex',
            width:60,
            align:"center",
            customRender:function (t,r,index) {
              return parseInt(index)+1;
            }
          },
          {
            title:'计划日期',
            align:"center",
            dataIndex: 'planDate',
            customRender:function (text) {
              return !text?"":(text.length>10?text.substr(0,10):text)
            }
          },
          {
            title:'计划表',
            align:"center",
            dataIndex: 'planSheet',
            scopedSlots: {customRender: 'fileSlot'}
          },
          {
            title:'发件状态',
            align:"center",
            dataIndex: 'sendState'
          },
          {
            title: '操作',
            dataIndex: 'action',
            align:"center",
            fixed:"right",
            width:147,
            scopedSlots: { customRender: 'action' }
          }
        ],
        url: {
          list: "/ProdPlan/prodPlan/list",
          delete: "/ProdPlan/prodPlan/delete",
          analysis: "/ProdPlan/prodPlan/analysis",
          report: "/ProdPlan/prodPlan/report",
          email: "/ProdPlan/prodPlan/email",
          deleteBatch: "/ProdPlan/prodPlan/deleteBatch",
          exportXlsUrl: "/ProdPlan/prodPlan/exportXls",
          importExcelUrl: "ProdPlan/prodPlan/importExcel",

        },
        dictOptions:{},
        superFieldList:[],
      }
    },
    created() {
      this.getSuperFieldList();
    },
    computed: {
      importExcelUrl: function(){
        return `${window._CONFIG['domianURL']}/${this.url.importExcelUrl}`;
      },
    },
    mounted() {
      this.initPie();
    },
    methods: {
      customRequest(options){
        let params = new FormData();
        params.append("file", options.file)
        params.append("plan")
        httpAction(this.url.importExcelUrl,params,'POST').then(res=>{
            if(res.success){
              this.$message.success(res.message)
              this.searchQuery()
            }else{
              this.$message.warning(res.message);
            }
        })

      },
      initDictConfig(){
      },
      getSuperFieldList(){
        let fieldList=[];
        fieldList.push({type:'date',value:'planDate',text:'计划日期'})
        fieldList.push({type:'string',value:'planSheet',text:'计划表',dictCode:''})
        fieldList.push({type:'int',value:'sendState',text:'发件状态',dictCode:''})
        this.superFieldList = fieldList
      },
      handleAnalysis: function (id) {
        var that = this;
        getAction(that.url.analysis, {id: id}).then((res) => {
          if (res.success) {
            that.$message.success(res.message);
          } else {
            that.$message.warning(res.message);
          }
        });
      },
      handleReport(id){
        let fileName = "导出文件"
        let pie = this.pieChart.getDataURL({
            type: 'png',
            pixelRatio: 2, // 设置像素比，提高清晰度
            backgroundColor: '#fff' // 设置背景色
          }).replace(/^data:image\/\w+;base64,/, '')

        downFile(this.url.report,{id: id,pie:pie},"POST").then((data)=>{
          if (!data) {
            this.$message.warning("文件下载失败")
            return
          }
          if (typeof window.navigator.msSaveBlob !== 'undefined') {
            window.navigator.msSaveBlob(new Blob([data],{type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'}), fileName+'.xlsx')
            // 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.openxmlformats-officedocument.spreadsheetml.sheet'}))
            // 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+'.xlsx')
            document.body.appendChild(link)
            link.click()
            document.body.removeChild(link); //下载完成移除元素
            window.URL.revokeObjectURL(url); //释放掉blob对象
          }
        })
      },
      handleEmal: function (id) {
        var that = this;
        let pie = that.pieChart.getDataURL({
            type: 'png',
            pixelRatio: 2, // 设置像素比，提高清晰度
            backgroundColor: '#fff' // 设置背景色
          }).replace(/^data:image\/\w+;base64,/, '')
        postAction(that.url.email, {id: id,pie:pie}).then((res) => {
          if (res.success) {
            that.$message.success(res.message);
          } else {
            that.$message.warning(res.message);
          }
        });
      },
      initPie(){
        this.pieChart = this.$echarts.init(this.$refs.pie)
        let option = {
          color: ['#70bfe5', '#eb6a6c', '#f9c942', '#91c974', '#5a6ac0'],
          tooltip: {
            trigger: 'item',
            formatter: '{a} <br/>{b}: {c} ({d}%)'
          },
          backgroundColor: '#fff',
          legend: {
            data: [
              '开发未完',
              '日别Capa不足',
              '合并生产',
              'LOT不良'
            ]
          },
          series: [
            {
              name: 'Access From',
              type: 'pie',
              selectedMode: 'single',
              radius: [0, '30%'],
              label: {
                position: 'inner',
                fontSize: 14
              },
              labelLine: {
                show: false
              },
              data: [
                { value: 280, name: 'R&D',itemStyle: {color:'#fc8251'} },
                { value: 494, name: '制造',itemStyle: {color:'#033E6B'}, selected: true }
              ]
            },
            {
              name: 'Access From',
              type: 'pie',
              radius: ['45%', '60%'],
              labelLine: {
                length: 30
              },
              label: {
                formatter: '{a|{b}}{abg|}\n{hr|}\n  {b|数量：}{c}  {per|{d}%}  ',
                backgroundColor: '#F6F8FC',
                borderColor: '#8C8D8E',
                borderWidth: 1,
                borderRadius: 4,
                rich: {
                  a: {
                    color: '#6E7079',
                    lineHeight: 22,
                    align: 'center'
                  },
                  hr: {
                    borderColor: '#8C8D8E',
                    width: '100%',
                    borderWidth: 1,
                    height: 0
                  },
                  b: {
                    color: '#4C5058',
                    fontSize: 14,
                    fontWeight: 'bold',
                    lineHeight: 33
                  },
                  per: {
                    color: '#fff',
                    backgroundColor: '#4C5058',
                    padding: [3, 4],
                    borderRadius: 4
                  }
                }
              },
              data: [
                { value: 280, name: '开发未完' ,itemStyle: {color:'#fc8251'}},
                { value: 376, name: '日别Capa不足',itemStyle: {color:'#25567B'} },
                { value: 40, name: '合并生产',itemStyle: {color:'#0B61A4'} },
                { value: 78, name: 'LOT不良',itemStyle: {color:'#66A3D2'} },
              ]
            }
          ]
        };
        this.pieChart.setOption(option)
      }
    }
  }
</script>
<style scoped>
  @import '~@assets/less/common.less';
</style>