<template>
  <div style="padding:10px">
    <q-card inline class="fit shadow-6">
      <q-card-main style="height:80%">
        <q-table
          ref="table"
          color="primary"
          :data="serverData"
          :columns="columns"
          separator="cell"
          selection="multiple"
          :selected.sync="selected"
          row-key="id"
          :pagination.sync="serverPagination"
          @request="request"
          :loading="loading"
          :rows-per-page-label="$t('Rows per page')"
          :rows-per-page-options="[5,10,20,30,40,50,60,200,500]"
          :no-data-label="$t('No data')"
        >
          <template slot="top-left" slot-scope="props">
            <q-input v-model="filter.name" type="text" prefix="标题：" />&nbsp;&nbsp;
            <div style="width: 180px; max-width: 90vw;">  <q-select       v-model="filter.type"    prefix="分类："   :options="kindlist"   clearable/></div>&nbsp;&nbsp;
             <div style="width: 180px; max-width: 90vw;">  <q-select       v-model="filter.status"    prefix="启用状态："   :options="yesnokindlist"   clearable/></div>&nbsp;&nbsp;
            <q-btn push dense color="primary" icon="search" @click="search">{{$t('Search')}}</q-btn>&nbsp;&nbsp;
            <!-- <q-btn push dense color="primary" icon="add" @click="addsaveAdv">{{$t('Add')}}</q-btn>&nbsp;&nbsp; -->
         <q-btn push dense color="primary" icon="add" @click="syslibraryadd">{{$t('Add')}}</q-btn>&nbsp;&nbsp;

          </template>
          <template slot="top-right" slot-scope="props">
            <q-btn
              flat
              round
              dense
              :icon="props.inFullscreen ? 'fullscreen_exit' : 'fullscreen'"
              @click="props.toggleFullscreen"
            />
          </template>
          <template slot="top-selection" slot-scope="props">
            <q-btn icon="create" color="positive" label="启用" @click="updateDAdvsStatuslist (1)" />&nbsp;&nbsp;
            <q-btn icon="create" color="negative" label="停用" @click="updateDAdvsStatuslist (0)" />
          </template>
          <q-td slot="body-cell-id" slot-scope="props" :props="props" style="width:200px">
            <q-btn
              small
              round
              push
              glossy
              dense
              icon="edit"
              color="primary"
              @click="editAdv(props.value,1)"
            ></q-btn>
            <q-btn
              small
              round
              push
              glossy
              dense
              icon="delete"
              color="red"
              @click="delAdv(props.value)"
            ></q-btn>
            <!--<q-btn-dropdown color="secondary" label="操作" no-wrap>
                <q-list link>
                  <q-item v-close-overlay @click.native="editAdv(props.value,1)" >
                    <q-item-main>
                      <q-item-tile sublabel>修改</q-item-tile>
                    </q-item-main>
                  </q-item>
                  <q-item v-close-overlay @click.native="delAdv(props.value)" >
                    <q-item-main>
                      <q-item-tile sublabel >删除</q-item-tile>
                    </q-item-main>
                  </q-item>
                  <q-item v-close-overlay>
                    <q-item-main>
                    <q-item-tile sublabel>关闭弹窗</q-item-tile>
                    </q-item-main>
                  </q-item>
                </q-list>
            </q-btn-dropdown>-->
          </q-td>
        </q-table>
      </q-card-main>
    </q-card>
    <!-- 新增修改页面 -->
    <q-modal v-model="editModal" maximized>
      <q-modal-layout>
        <q-toolbar slot="header">
          <q-btn flat round dense @click="editModal = false" icon="reply" />
          <q-toolbar-title v-if="subtype=='edit'">{{$t('Edit')}}</q-toolbar-title>
          <q-toolbar-title v-if="subtype=='add'">{{$t('Add')}}</q-toolbar-title>
        </q-toolbar>
        <q-toolbar slot="footer">
          <q-toolbar-title></q-toolbar-title>
          <q-btn round color="red" @click="saveUpdateAdv" v-if="subtype=='edit'">{{$t('Save')}}</q-btn>
          <q-btn round color="red" @click="saveAdv" v-if="subtype=='add'">{{$t('Add')}}</q-btn>
          <q-btn round  @click="editModal = false">{{$t('Cancel')}}</q-btn>
        </q-toolbar>
        <div class="layout-padding">
          <q-field class="liststype">
            <q-input v-model="tempAdv.title" float-label="标题" />
          </q-field>
          <q-field class="liststype">
            <q-select v-model="tempAdv.type" :options="kindlist" float-label="分类" />
          </q-field>
          <q-field class="liststype">
            <q-select v-model="tempAdv.status" :options="yesnokindlist" float-label="启用" />
          </q-field>
          <q-field class="liststype">
            <!-- <q-input v-model="tempAdv.content" float-label="描述" /> -->
             <tinymce :value='tempAdv.content'  v-model="tempAdv.content"></tinymce>

          </q-field>
        </div>
      </q-modal-layout>
    </q-modal>
  </div>
</template>

<script>
import {
  getAdvPagedList,
  delAdv,
  updateAdvStatus,
  saveAdv,
  editAdv,
  loadAdv,
  updateAdvsStatus,
  getSysAdvListByTypeAndNum,
  uploadfile
} from "@/service/library/syslibrary";
import { getSysCodelistByKindcode } from "@/service/syscodelist/syscodelist";
import tinymce from '../../components/tinymceEditor.vue';
const uploadpath = "http://nw.sy-metro.com:6104/uploadfileadmin/manager";
export default {
	components: {tinymce},
  name: "sysadv",
  data() {
    return {
      uploadurl:
        uploadpath + "/znzl/file/upload/videoandimgurl?uploadPar=library&",
      serverData: [],
      menuModal: false,
      tempFunction: {
        id: 0,
        name: "",
        moduleId: 0,
        module: "",
        code: "",
        description: ""
      },
      serverPagination: {
        page: 1,
        rowsNumber: 0, // specifying this determines pagination is server-side
        rowsPerPage: 10 // current rows per page being displayed
      },
      nextserverPagination: {
        page: 1,
        rowsNumber: 0, // specifying this determines pagination is server-side
        rowsPerPage: 100 // current rows per page being displayed
      },
      yeornoOptions: [],
      columns: [
        {
          name: "title",
          required: true,
          label: "标题",
          align: "left",
          field: "title",
          sortable: false
        },
        {
          name: "statusname",
          label: "启用状态",
          field: "statusname",
          sortable: false,
          align: "center"
        },
        {
          name: "typename",
          label: "分类",
          field: "typename",
          sortable: false,
          align: "center"
        },
        {
          name: "id",
          required: true,
          label: this.$t("ID"),
          align: "center",
          field: "id"
        }
      ],
      filter: {
        name: "",
        pid: "",
        type:"",
        status:"",
        content:""
      },
      selected: [],
      kindlist: [],
      yesnokindlist: [],
      loading: false,
      editModal: false,
      subtype: "add",
      fileCount: 0,
      tempAdv: {
        id: "",
        title: "",
        status: "",
        statusname: "",
        ctime: "",
        type: "",
        typename: "",
        content: ''
      }
    };
  },
  methods: {
    async request(props) {
      this.loading = true;
      this.serverPagination = props.pagination;
      let table = this.$refs.table,
        { page, rowsPerPage, sortBy, descending } = props.pagination;
      let query = {
        pageNum: page,
        pageSize: rowsPerPage,
        sortBy: sortBy,
        descending: descending,
        title: this.filter.name,
        type:this.filter.type,
        status:this.filter.status
        // account: this.filter.account,
        // phoneNumber: this.filter.phoneNumber
      };

      let dataRes = await getAdvPagedList(query);
      let data = dataRes.data.data;

      this.serverPagination.rowsNumber = data.total;
      this.serverData = data.list;
      this.getSysAdvListByTypeAndNum();
       this.getCodelistByKindcode();
      this.getYesNoCodelistByKindcode();
      setTimeout(() => {
        this.loading = false;
      }, 500);
    },
    upload() {
      this.$q.notify({
        icon: "cloud_upload",
        color: "secondary",
        message: "Hmm, will upload at another time, ok?"
      });
    },
    async delAdv(id) {
      try {
        await this.$q.dialog({
          title: "删除操作",
          message: this.$t("Comfirm do it"),
          position: "right",
          ok: {
            push: true,
            label: "确认"
          },
          cancel: {
            push: true,
            color: "negative",
            label: "取消"
          }
        });
        await delAdv({ id: id });
        this.$q.notify({
          type: "positive",
          message: this.$t("Successfully"),
          position: "bottom-right"
        });
        this.search();
      } catch (e) {}
    },
    /**
     * 批量更新状态
     */
    async updateDAdvsStatuslist(type) {
      try {
        await this.$q.dialog({
          title: this.$t("Batch do it"),
          message: this.$t("Comfirm do it"),
          ok: {
            push: true,
            label: "提交"
          },
          cancel: {
            push: true,
            color: "negative",
            label: "取消"
          }
        });
        let idlist = this.selected.map(s => {
          return s.id;
        });
        await updateAdvsStatus(idlist.join(","), type);
        this.$q.notify({
          type: "positive",
          message: this.$t("Successfully"),
          position: "bottom-right"
        });
        this.selected = [];
        this.search();
      } catch (e) {}
    },
    async getSysAdvListByTypeAndNum() {
      let data = await getSysAdvListByTypeAndNum("2", "1");
    },
    /**用户修改 */
    editAdv(id, type) {
      this.$router.push({
      	path: '/syslibraryedit',
      	query: {
      		'id':id,
      	}
      });
     // 
     //  this.subtype = "edit";
     //  let editAdv = this.serverData.filter(s => {
     //    return s.id === id;
     //  });

     //  if (editAdv && editAdv.length > 0) {
     //    this.tempAdv = JSON.parse(JSON.stringify(editAdv[0]));
     //  } else {
     //    return true;
     //  }
     //  this.editModal = true;
    },
    async saveUpdateAdv() {
      if (
        this.tempAdv.title == null ||
        this.tempAdv.type == null ||
        this.tempAdv.title == "" ||
        this.tempAdv.type == ""
      ) {
        this.$q.notify({
          message: "请完善信息，标题和类别不能为空",
          type: "negative",
          icon: "error_outline",
          timeout: 3000,
          position: "center"
        });
        return false;
      }
      await editAdv(this.tempAdv);
      this.$q.notify({
        type: "positive",
        message: this.$t("Saved successfully"),
        position: "bottom-right"
      });
      this.editModal = false;
      this.search();
    },
    search() {
      this.request({
        pagination: this.serverPagination,
        filter: this.filter
      });
    },
    /**
     * 更新用户
     */
    async saveAdv() {
      if (
        this.tempAdv.title == null ||
        this.tempAdv.type == null ||
        this.tempAdv.title == "" ||
        this.tempAdv.type == ""
      ) {
        this.$q.notify({
          message: "请完善信息，标题和分类不能为空",
          type: "negative",
          icon: "error_outline",
          timeout: 3000,
          position: "center"
        });
        return false;
      }

      this.tempAdv.pid = this.pid;
      
      await saveAdv(this.tempAdv);
      this.$q.notify({
        type: "positive",
        message: this.$t("Saved successfully"),
        position: "bottom-right"
      });
      this.editModal = false;
      this.search();
    },
    search() {
      this.request({
        pagination: this.serverPagination,
        filter: this.filter
      });
    },
    addsaveAdv() {
      this.pid = "1";
      this.tempAdv = {};
      this.tempAdv.status = "1";
      this.tempAdv.content = "";
      this.tempAdv.isjump = "0";
      this.subtype = "add";
      this.editModal = true;

    },
    async getCodelistByKindcode() {
      this.kindlist = [];
      let kindlist_code = await getSysCodelistByKindcode("LIBRARY_TYPE");
      if (kindlist_code.data.data.length > 0) {
        for (var item of kindlist_code.data.data) {
          let obj = {
            label: item.codename,
            value: item.codevalue
          };
          this.kindlist.push(obj);
        }
      }
    },
    async getYesNoCodelistByKindcode() {
      this.yesnokindlist = [];
      //  this.yeornoOptions=[];
      let kindlist_code = await getSysCodelistByKindcode("YES_NO");
      if (kindlist_code.data.data.length > 0) {
        for (var item of kindlist_code.data.data) {
          let obj = {
            label: item.codename,
            value: item.codevalue
          };
          this.yesnokindlist.push(obj);
          // this.yeornoOptions.push(obj);
        }
      }
    },
    async getSignedUrl(file) {
      let uploadurl = this.uploadurl;
      const contentType = file.type; // 发送正确的Content-Type
      const fileName = file.name; // 如果你想使用这个值来计算S3密钥。
      let response = await uploadfile({ fileName, contentType });

      // const response = await api.getSignedUrl({ fileName, contentType }); // 你的API向一个计算的服务器请求调用
      // return response.data.url;
    },
    //新增
    syslibraryadd(){
    this.$router.push("/syslibraryadd");
    },
    attachmentUploaded(file, xhr) {
      let res = JSON.parse(xhr.response).path;
      this.fileCount++;
      if (res != "") {
        this.$q.notify({
          message: "上传成功",
          type: "positive",
          icon: "done",
          timeout: 1000,
          position: "top-right"
        });
        this.tempAdv.imgurl = res;
        console.log(res);
        if (this.fileCount > 1) {
          var cNode = document.getElementsByClassName("q-uploader-files")[0];
          cNode.removeChild(cNode.childNodes[0]);
        }
      } else {
        this.$q.notify({
          message: res.msg,
          type: "negative",
          icon: "error_outline",
          timeout: 3000,
          position: "top-right"
        });
      }
    }
  },

  mounted() {
    this.request({
      pagination: this.serverPagination,
      filter: this.filter
    });
  },
      watch: {
      '$route'(to, from) {
      	           this.request({
      pagination: this.serverPagination,
      filter: this.filter
    });
      }
    },
};
</script>
<style scoped>
.liststype {
  width: 98%;
  /* padding-left: 4%; */
  /* float: left; */
}
</style>
