<style>
  #wps-iframe {
    height: 100%
  }
</style>
<template>
  <a-card :bordered="false">
    <!-- 查询区域 -->
    <div class="table-page-search-wrapper">
      <a-form layout="inline">
        <a-row :gutter="24">
          <a-col :md="6" :sm="8">
            <selectTable :projectId.sync="queryParam.projectId"></selectTable>
          </a-col>
          <a-col :md="6" :sm="8">
            <a-form-item label="脚本名称">
              <a-input placeholder="请输入脚本名称" v-model="queryParam.name"></a-input>
            </a-form-item>
          </a-col>
          <a-col :md="6" :sm="8">
            <a-form-item label="创建人">
              <!-- <a-input placeholder="请输入创建人" v-model="queryParam.creator_dictText"></a-input> -->
              <a-select v-model="queryParam.creator" showSearch allowClear placeholder="请选择创建人"
                optionFilterProp="children" style="width: 100%" :filterOption="true">
                <a-select-option v-for="appModel in options" :key="appModel.userId + new Date().getTime()"
                  :value="appModel.userId">
                  {{ appModel.realName }}
                  &#12288;&#12288;{{ appModel.roleName }}</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <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>
            </span>
          </a-col>

        </a-row>
      </a-form>
    </div>
    <div style="float:right;margin:0 0 20px 20px">
      <a-upload name="file" :multiple="false" :action="uploadAction" :headers="tokenHeader" :showUploadList="false"
        :beforeUpload="beforeUpload" @change="handleChange" style="margin-right:20px">
        <a-button :disabled="loadingElse">
          <a-icon type="upload" />
          {{loadingElse?'上传中,请稍后':'文件上传'}}
        </a-button>
      </a-upload>
      <a-dropdown placement="bottomRight">
        <a-button>新增</a-button>
        <a-menu slot="overlay">
          <a-menu-item>
            <a-icon type="file-word" /><span style="text-align: center" @click="creatWps('word')">文字文档</span>
          </a-menu-item>
          <a-menu-item>
            <a-icon type="file-excel" /><span style="text-align: center" @click="creatWps('excel')">表格文档</span>
          </a-menu-item>
          <a-menu-item>
            <a-icon type="file-ppt" /><span style="text-align: center" @click="creatWps('ppt')">演示文档</span>
          </a-menu-item>

          <!-- <a-menu-item>
            <a target="_blank" rel="noopener noreferrer" href="http://www.alipay.com/">1st menu item</a>
          </a-menu-item>
          <a-menu-item>
            <a target="_blank" rel="noopener noreferrer" href="http://www.taobao.com/">2nd menu item</a>
          </a-menu-item>
          <a-menu-item>
            <a target="_blank" rel="noopener noreferrer" href="http://www.tmall.com/">3rd menu item</a>
          </a-menu-item> -->
        </a-menu>
      </a-dropdown>
    </div>
    <div style="clear:both"></div>
    <div>
      <a-table ref="table" size="middle" bordered rowKey="name" :columns="columns" :dataSource="dataSource"
        :pagination="ipagination" :loading="loading" @change="handleTableChange">
        <span slot="modifyTime" slot-scope="text">{{text|getDate}}</span>
        <span slot="size" slot-scope="text">{{text|sizeShow}}</span>
        <span slot="projectId_dictText" slot-scope="text">{{text?text:'-'}}</span>
        <span slot="action" slot-scope="text, record">
          <a @click="getViewUrlDbPath(record)">编辑</a>
          <a-divider type="vertical" />
          <a @click="bindProject(record)">项目绑定</a>
          <a-divider type="vertical" />
          <a-popconfirm title="确定删除吗?" @confirm="() => handleDelete(record.id)">
            <a>删除</a>
          </a-popconfirm>
        </span>

      </a-table>
    </div>
    <!-- <div id="show"></div> -->
    <a-modal :maskClosable="false" :title="type=='add'?'脚本新建':'脚本编辑'" v-model="visibleBind" :width="1200"
      :footer="null">

      <iframe :src="src" frameborder="0" style="width:100%;height:600px" v-if="type=='add'"></iframe>
      <div id="showWps" style="height:600px" v-show="type=='edit'"></div>


    </a-modal>
    <a-modal :maskClosable="false" title="绑定项目" v-model="visibleProject" @ok="handleOk">
      <span>项目选择：</span>
      <a-select v-model="projectId" showSearch style="width:300px" optionFilterProp="children"
        :filterOption="filterOption">
        <a-select-option :value="item.projectId" v-for="item of dataElse" :key="item.id">
          {{ item.projectName }}&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;{{
                item.mediaId == "1" ? '头条' :item.mediaId == "2"? '快手':item.mediaId == "3"?'头条内广':'快手内广'
              }}&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;{{ item.advertiserName }}
        </a-select-option>
      </a-select>
    </a-modal>
    <!-- table区域-end -->

    <!-- 表单区域 -->
    <wpsFile-modal ref="modalForm" @ok="modalFormOk"></wpsFile-modal>

  </a-card>
</template>

<script>
  import {
    getAction,
    postAction,
    postFile,
    deleteAction,
    putAction
  } from '@/api/manage'
  import selectTable from '@/views/modules/Statistics/components/selecTable.vue'
  import WpsFileModal from './modules/WpsFileModal'
  import {
    mapGetters
  } from 'vuex'
  import {
    JeecgListMixin
  } from '@/mixins/JeecgListMixin'
  import qs from 'qs';
  const fileSuffix = [
    'xls', 'xlt', 'et', 'xlsx', 'xltx', 'csv', 'xlsm', 'xltm',
    'doc', 'dot', 'wps', 'wpt', 'docx', 'dotx', 'docm', 'dotm',
    'ppt', 'pptx', 'pptm', 'ppsx', 'ppsm', 'pps', 'potx', 'potm', 'dpt', 'dps',
    'pdf'
  ];
  export default {
    name: "WpsFileList",
    mixins: [JeecgListMixin],
    components: {
      WpsFileModal,
      selectTable
    },
    data() {
      return {
        description: 'wps文件管理页面',
        dataElse: [],
        projectId: '',
        visibleProject: false,
        // 表头
        visibleBind: false,
        wpsType: 'word',
        type: "add",
        uploadAction: "http://api.tjyourong.com.cn/jeecg-boot/ctop/wpsFile/uploadFile",
        columns: [{
            title: '脚本名称',
            align: "center",
            dataIndex: 'name'
          },
          {
            title: '文件大小(KB)',
            align: "center",
            dataIndex: 'size',
            scopedSlots: {
              customRender: 'size'
            },
          },
          {
            title: '绑定项目',
            align: "center",
            dataIndex: 'projectId_dictText',
            scopedSlots: {
              customRender: 'projectId_dictText'
            },
          },
          {
            title: '创建人',
            align: "center",
            dataIndex: 'creator_dictText'
          },
          {
            title: '发布时间',
            align: "center",
            dataIndex: 'modifyTime',
            scopedSlots: {
              customRender: 'modifyTime'
            },
          },
          {
            title: '操作',
            dataIndex: 'action',
            align: "center",
            scopedSlots: {
              customRender: 'action'
            },
          }
        ],
        url: {
          list: "/ctop/wpsFile/list",
          delete: "/ctop/wpsFile/delete",
          deleteBatch: "/ctop/wpsFile/deleteBatch",
          exportXlsUrl: "ctop/wpsFile/exportXls",
          importExcelUrl: "ctop/wpsFile/importExcel",
        },
        src: "",
        loadingElse: false,
        fileId: '',
        loadingOk: false,
        options: []
      }
    },
    computed: {
      importExcelUrl: function () {
        return `${window._CONFIG['domianURL']}/${this.url.importExcelUrl}`;
      }
    },
    watch: {
      visibleBind(n, o) {
        if (!n) {
          this.src = ''
          this.loadData(1)
        }
      }
    },
    filters: {
      getDate(value) {
        let date = new Date(value)
        let y = date.getFullYear()
        let MM = date.getMonth() + 1
        MM = MM < 10 ? '0' + MM : MM
        let d = date.getDate()
        d = d < 10 ? '0' + d : d
        return y + '-' + MM + '-' + d
      },
      sizeShow(value) {
        return (value / 1024).toFixed(2)
      }
    },
    mounted() {
      this.getParticipateList()
      getAction('/sys/user/getAllUserList', '').then(res => {
        if (res.success) {
          this.options = res.result
        }
      })
    },
    methods: {
      filterOption(input, option) {
        return option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
      },
      ...mapGetters(['nickname', 'avatar', 'userInfo']),
      getParticipateList() {
        getAction('/ctop/projectMember/participateList', {
          userId: this.userInfo().id
        }).then(res => {
          if (res.code == 0) {
            this.dataElse = res.result
          }
        })
      },
      beforeUpload(file) {
        this.loadingElse = true
        const size = (Number(file.size) / (1024 * 1024)).toFixed(2);
        const fileName = file.name;
        const fileStrArr = fileName.split(".");
        const suffix = fileStrArr[fileStrArr.length - 1];

        let result = fileSuffix.some((item) => {
          return item === suffix
        });

        if (!result) {
          this.$message.error("不支持该文件类型");
          this.loadingElse = false
          return false;
        }

        if (size > 10) {
          this.$message.error("文件不能大于10MB");
          this.loadingElse = false
          return false;
        }
      },
      handleChange(info) {

        if (info.file.status !== 'uploading') {
          console.log(info.file, info.fileList);
        }
        if (info.file.status === 'done') {
          this.$message.success(`${info.file.name} 上传成功`);
          this.loadingElse = false
          this.loadData(1)
        } else if (info.file.status === 'error') {
          this.$message.error(`${info.file.name} file upload failed.`);
          this.loadingElse = false
        }
      },
      handleOk(e) {
        this.loadingOk = true
        var params = qs.stringify({
          projectId: this.projectId,
          fileId: this.fileId
        })
        postAction('/ctop/wpsFile/bindProject', params).then(res => {
          if (res.success) {
            this.visibleProject = false
            this.projectId = ""
            this.loadingOk = false
            this.loadData()
          } else {
            this.$message.error('绑定失败')
            this.loadingOk = false
          }
        })
      },
      creatWps(type) {
        console.log(type)
        this.visibleBind = true
        this.wpsType = type
        this.type = 'add'
        getAction('/ctop/wpsFile/createTemplateFile', {
          template: type
        }).then(res => {
          console.log(res)
          if (res.code == 200) {
            this.src = res.msg;
            console.log(this.src)
          } else {
            this.$message.error('请求错误！')
          }
        })
        // getCreateFilePath({
        //   template: type
        // }).then(res => {
        //   console.log(res)
        //   // if (res.data.data){
        //   this.src = res.data.msg;
        //   // }else {
        //   // this.showErrMeg('请求错误！');
        //   // }
        // }).catch(() => {
        //   this.showErrMeg('请求错误！');
        // });

      },

      bindProject(item) {
        this.visibleProject = true
        this.projectId = ''
        this.fileId = item.id
        // this.getParticipateList()
      },
      getViewUrlDbPath(item) {
        // this.loading = true;
        const params = {
          fileId: item.id,
          userId: item.creator
        };
        getAction('/v1/api/file/getViewUrlDbPath', params).then((res) => {
          console.log(res)
          if (res.data) {
            let r = res.data;
            this.visibleBind = true
            // this.src = r.wpsUrl;
            this.type = 'edit'
            this.openWps(r.wpsUrl, r.token)

          } else {
            this.$message.error('请求错误')
          }
        })
      },
      openWps(url, token) {

        this.$nextTick(() => {
          let _this = this;
          const wps = _this.wps.config({
            mode: 'simple',
            mount: document.querySelector('#showWps'),
            wpsUrl: url,
          });
          wps.setToken({
            "token": token
          });
          let app = wps.Application;
        })
      }
    }
  }
</script>
<style scoped>
  @import '~@assets/less/common.less';
</style>