<template>
  <a-card :bordered="false">
    <!-- 查询区域 -->
    <div class="table-page-search-wrapper">
      <a-form layout="inline" @keyup.enter.native="searchQuery">
        <a-row :gutter="24">
          <!--循环输出搜素条件-->
          <a-col v-for='(item,i) in searchList' :xl="6" :lg="7" :md="8" :sm="24">
            <a-form-item :label='item.showName' v-if='item.rule==null || item.rule==""'> <!--规则为空显示输出框-->
              <a-input :placeholder="item.showName" v-model="item.value"></a-input>
            </a-form-item>

            <a-form-item :label='item.showName' v-if='item.rule!=""'> <!--规则不为空用下拉显示-->
              <a-select v-model="item.value" :placeholder="item.showName" >
                <a-select-option
                  :value='_item.value'
                  v-for='(_item,i) in item.ruleMap'
                >
                  {{_item.text}}
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-col>

        </a-row>
      </a-form>
    </div>
    <!-- 查询区域-END -->

    <!-- 操作按钮区域 -->
    <div class="table-operator">
<!--      <a-button @click="handleAdd" type="primary" icon="plus">{{description}}</a-button>-->
      <a-button type="primary" @click="searchQuery" icon="search">查询</a-button>
      <a-button type="primary" icon="download" @click="runExport()">导出</a-button>
      <a-button type="primary" icon="download" @click="viewExport()">查看</a-button>
<!--      <a-upload name="file" :showUploadList="false" :multiple="false" :headers="tokenHeader" :action="importExcelUrl" @change="handleImportExcel">-->
<!--        <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">
          <span v-if="!text" style="font-size: 12px;font-style: italic;">无图片</span>
          <img v-else :src="getImgView(text)" 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)">
            下载
          </a-button>
        </template>

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

          <a-divider type="vertical" />
          <a-dropdown>
            <a class="ant-dropdown-link">更多 <a-icon type="down" /></a>
            <a-menu slot="overlay">
              <a-menu-item>
                <a @click="handleDetail(record)">详情</a>
              </a-menu-item>
              <a-menu-item>
                <a-popconfirm title="确定删除吗?" @confirm="() => handleDelete(record.id)">
                  <a>删除</a>
                </a-popconfirm>
              </a-menu-item>
            </a-menu>
          </a-dropdown>
        </span>

      </a-table>
    </div>
  <GtExportHisList :show='viewShow' :exportId='exportId' ref='testRef'
  @_123cloase='_123cloase'
  ></GtExportHisList>
  </a-card>
</template>

<script>

  import '@/assets/less/TableExpand.less'
  import { mixinDevice } from '@/utils/mixin'
  import { JeecgListMixin } from '@/mixins/JeecgListMixin'
  import { httpAction } from '@/api/manage'
  import GtExportHisList from './modules/GtExportHisList'


  export default {
    name: 'GtExportPage',
    mixins:[JeecgListMixin, mixinDevice],
    components: {
      GtExportHisList
    },
    data () {
      return {
        description: '导出功能页面',
        exportId:0,
        showExportBtn:false,
        viewShow:false,
        searchList:[
          // {showName:"测试输入",rule:"",filedName:"test"},
          // {showName:"测试选择",rule:[{value:1,text:'男3'},{value:2,text:'女2'}],filedName:"test"}
        ],
        queryParams:{},
        // 表头
        columns: [
          // {
          //   title: '#',
          //   dataIndex: '',
          //   key:'rowIndex',
          //   width:60,
          //   align:"center",
          //   customRender:function (t,r,index) {
          //     return parseInt(index)+1;
          //   }
          // },
          // {
          //   title:'A',
          //   align:"center",
          //   dataIndex: 'deptName'
          // },
          // {
          //   title:'B',
          //   align:"center",
          //   dataIndex: 'deptSimpleName'
          // },
          // {
          //   title:'C',
          //   align:"center",
          //   dataIndex: 'areaId'
          // }
        ],
        url: {
          columnUrl: "/export/gtExport/pageColumns",
          list: "/export/gtExport/pageList",
          downloadUrl:"/sys/common/static/",
          runExportUrl:"/export/gtExport/runExport",
          queryParamUrl:"/export/gtExport/queryParamList"

        },
        dictOptions:{},
        superFieldList:[],
      }
    },
    created() {
    //this.getSuperFieldList();

      let _exportId = this.$route.query.exportId;
      if (!_exportId) {
        _exportId = this.getUrlKey('exportId',this.$route.fullPath);
      }
      console.info('1.初始化查询是否存在exportId:'+_exportId);
      this.exportId = _exportId;
      this.url.list = "/export/gtExport/pageList?exportId="+this.exportId;
      if (this.exportId!=undefined && this.exportId!="") {
        this.initDynamicTable()
      }
    },
    watch:{
      $route:{
        handler(to) {
          this.exportId = to.query.exportId;
          this.url.list = "/export/gtExport/pageList?exportId="+this.exportId;
          if (this.exportId!=undefined && this.exportId!="") {
            this.initDynamicTable()
          }
        }
      }

    },
    computed: {
      importExcelUrl: function(){
        return `${window._CONFIG['domianURL']}/${this.url.importExcelUrl}`;
      },
    },
    methods: {
      _123cloase(){
        this.viewShow = false;
      },
      getUrlKey(name,url){
        return decodeURIComponent((new RegExp('[?|&]' + name + '=' + '([^&;]+?)(&|#|;|$)').exec(url) || [, ""])[1].replace(/\+/g, '%20')) || null
      },
      initDictConfig(){
      },
      runExport(){
        this.$message.info('开始导出')
        //queryParams 更新
        this.getParam();
        this.queryParam["exportId"]=this.exportId;
        httpAction(this.url.runExportUrl,this.queryParam,"POST").then((data)=>{
          if ('200' == data.code) {
            console.info("开始导出");
          }
        });
      },
      viewExport(){
        this.viewShow = true;
        this.$set(this,"exportId",this.exportId);
        let url = "/export/gtExportHis/list"+"?exportId="+this.exportId;

        this.$refs.testRef.setUrl(url);
        this.$refs.testRef.loadData();
      },
      initDynamicTable(){
        let that = this;
        console.info("exportId"+that.exportId)
        //初始化搜素
        that.queryParamList();
        //初始化列
        httpAction(this.url.columnUrl,{"exportId":that.exportId},"POST").then((data)=>{
          console.info(data);
          let _array = [
            {
              title: '#',
              dataIndex: '',
              key:'rowIndex',
              width:60,
              align:"center",
              customRender:function (t,r,index) {
                return parseInt(index)+1;
              }
            }];
          data.result.forEach((obj,index)=>{
            if (obj.isShow == 0) {//不显示的跳过

            }else{
              _array.push({
                title:obj.showName,
                align:"center",
                dataIndex:obj.fieldName,
                hide: obj.isShow==0?true:false

              })
            }

          })
          that.columns = _array;

        })
        //初始化table
      },
      getSuperFieldList(){
        let fieldList=[];
        fieldList.push({type:'string',value:'deptName',text:'部门全称',dictCode:''})
        fieldList.push({type:'string',value:'deptSimpleName',text:'部门简称',dictCode:''})
        fieldList.push({type:'string',value:'areaId',text:'所属地区'})
        fieldList.push({type:'string',value:'parentDeptId',text:'上级部门',dictCode:''})
        this.superFieldList = fieldList
      },
      downloadFile(filePath,fileName){
        downFile(this.url.downloadUrl+filePath,{}).then((data)=>{
          if (!data) {
            this.$message.warning("文件下载失败")
            return
          }
          if (typeof window.navigator.msSaveBlob !== 'undefined') {
            window.navigator.msSaveBlob(new Blob([data],{type: 'application/vnd.ms-excel'}), fileName)
          }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对象
          }
        })
      },
      queryParamList(){
        let that = this;
        httpAction(this.url.queryParamUrl+"?exportId="+that.exportId,{},"GET").then((data)=>{
          if ('200' == data.code) {
            //获取到搜素列表对象;
            //然后赋值到searchList
            data.result.forEach((item,index)=>{
              console.info(item);
              if (item.isMust&&item.ruleMap&&item.ruleMap.length!=0) {
                item.value = item.ruleMap[0].value;
              }
            })
            that.searchList = data.result;
            that.searchQuery();
          }
        });
      },
      searchQuery(){
        let _that = this;
        //queryParams 更新
        _that.getParam();
        _that.loadData();
      },
      getParam(){
        let _that = this;
        _that.queryParam={};
        console.info(_that.searchList);
        _that.searchList.forEach(item=>{
          let _name = "param@"+item.fieldName;
          if (item.value&&item.value!="") {
            _that.queryParam[_name]=item.value;
          }
        })
        console.info(_that.queryParam);
      }
    }
  }
</script>
<style scoped>
  @import '~@assets/less/common.less';
</style>