<template>
    <div>
      <el-breadcrumb separator=">">
        <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item>
          <a href="#">基础信息管理</a>
        </el-breadcrumb-item>
        <el-breadcrumb-item>
          模板管理
        </el-breadcrumb-item>
      </el-breadcrumb>
      <el-divider></el-divider>
      <!--
        要resetFields起作用，必须配置:model和prop
      -->
      <el-form ref="queryForm" :model="queryModel" inline class="demo-form-inline">
        <el-form-item label="年份" prop="year">
            <el-date-picker
              v-model="queryModel.year"
              size="mini"
              type="year"
              placeholder="选择年"
              value-format="yyyy"
              format="yyyy">
            </el-date-picker>
          </el-form-item>
        <el-form-item label="标题" prop="title">
          <el-input type="text" size="mini" v-model="queryModel.title"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button
            type="primary"
            size="mini"
            icon="ios-search"
            @click="changePage(1)"
            :loading="loading"
          >查询</el-button>&nbsp;
          <el-button
            type="info"
            size="mini"
            style="margin-left: 8px"
            @click="handleReset('queryForm')"
          >重置</el-button>&nbsp;
        </el-form-item>
      </el-form>
      <el-divider></el-divider>
      <el-table
        :data="tableData"
        style="min-height:400px;"
        v-loading="loading"
        stripe
        @sort-change="sortChange"
      >
        <el-table-column  prop="year"  label="所属年份"></el-table-column>
        <el-table-column  prop="title"  label="标题" width="300"></el-table-column>
        <el-table-column  prop="subtitle"  label="副标题"></el-table-column>
        <el-table-column  prop="type"  label="模板类型">
            <template slot-scope="{row}">
                <span v-if="row.type=='1'">收入</span>
                <span v-else-if="row.type=='2'">支出</span>
            </template>
        </el-table-column>
        <el-table-column  prop="status"  label="状态">
          <template slot-scope="{row}">
                <span v-if="row.status=='0'" style="color:#F56C6C">未审核</span>
                <span v-else-if="row.status=='1'" style="color:#67C23A">已审核</span>
            </template>
        </el-table-column>
        <el-table-column  prop="attachment"  label="附件">
          <template slot-scope="scope">
            <el-link type="primary" :href="scope.row.attachment" target="_blank" :underline="false">
            <el-image
              style="width: 40px; height: 40px"
              v-if="scope.row.attachment&&isImageFile(scope.row.attachment)"
              :src="scope.row.attachment"
              fit="fit">
            </el-image>
            <span v-else>
              <span v-if="scope.row.attachment">附件</span>
            </span>
            </el-link>
          </template>
        </el-table-column>
        <el-table-column  prop="attachment"  label="上传">
          <template slot-scope="scope">
              <el-upload
                  class="avatar-uploader"
                  name="photoFile"
                  :action="uploadUrl"
                  :show-file-list="false"
                  :headers="headers"
                  :data="uploadData"
                  :on-success="($event) =>{handleAvatarSuccess($event,scope.row)}"
                  :before-upload="beforeAvatarUpload"
                >
              <el-link type="primary">上传</el-link>
            </el-upload>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="500">
          <template slot-scope="{row}" >
            <el-button v-if="row.attachment&&row.status=='0'" size="mini" type="warning" @click="handleSave(row)">保存附件</el-button>
            <el-button size="mini" type="primary" @click="handleOption(row)">模板选项</el-button>
            <el-button size="mini" type="warning" @click="handleDateRange(row)">日期范围</el-button>
            <permission-detect class="inline" style="display:inline;margin-left:5px" path="/base/templateDepartment/Checked" method="post">
              <el-button v-if="row.status=='0'" size="mini" type="success" @click="handleChecked(row)">审核</el-button>
            </permission-detect>
            <permission-detect class="inline" style="display:inline;margin-left:5px" path="/base/fundIncomeInfo/generateData" method="post">
              <el-button type="danger"
              v-if="row.status=='1'"
              size="mini" 
              icon="el-icon-s-data" 
              @click="handleGenerateData(row.id)"
              >生成模板项目</el-button>
            </permission-detect>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        :current-page.sync="pageIndex"
        :total="totalElements"
        :page-sizes="pageSizeList"
        @current-change="changePage"
        @size-change="pageSizeChange"
        layout="total, sizes, prev, pager, next, jumper"
      ></el-pagination>
      <templateDepartment-detail
        v-if="showModal2"
        ref="userDetail"
        :businessKey="businessKey"
        :title="modalTitle2"
        @close="onDetailModalClose2"
      ></templateDepartment-detail>
      <templateDepartment-edit-date
        v-if="showModal3"
        ref="userDetail"
        :businessKey="businessKey"
        :title="modalTitle3"
        @close="onDetailModalClose3"
      ></templateDepartment-edit-date>
      <!-- <el-dialog
      title="选择生成年份"
      :visible.sync="batchImportVisible2"
      :modal-append-to-body="false"
      style="text-align: left"
      :close-on-click-modal="false"
    >
      <el-form label-width="150px" >
        <el-form-item label="年份" prop="selectYear">
          <el-date-picker
            v-model="selectYear"
            type="year"
            placeholder="选择年"
            value-format="yyyy"
            format="yyyy">
          </el-date-picker>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="batchImportVisible2 = false"
          >关 闭</el-button
        >
        <el-button type="danger" @click="handleGenerateData(selectTamplateId,selectYear)" :loading="submitting"
          >生 成</el-button
        >
      </div>
    </el-dialog> -->

    </div>
  </template>
  <script>
  import Constant from "@/constant";
  import templateInfoApi from "@/api/base/templateInfo";
  import fundIncomeInfoApi from "@/api/base/fundIncomeInfo";
  import templateDepartmentDetail from "./templateDepartment-detail";
  import templateDepartmentEditDate from "./templateDepartment-edit-date";
  import { getToken } from "@/utils/auth"; // get token from cookie
  
  export default {
    name: 'baseTemplateDepartmentList',
    data() {
      var self = this;
  
      return {
        queryModel: {
          title: "",
          year:"",
        },
        loading: false,
        tableData: [],
        pageIndex: 1,
        pageSize: 10,
        totalPages: 0,
        totalElements: 0,
        field: "",
        direction: "",
        pageSizeList: [10, 20, 30],
        multipleSelection: [],
        modalTitle: "",
        modalTitle2: "",
        modalTitle3: "",          
        businessKey: "",
        showModal: false,
        showModal2:false,
        showModal3:false,
        dialogFormVisible:false,
        newPassword:"",
        roleResult:[],
        props: {
          // 配置项（必选）
          value: "id",
          label: "name",
          children: "children"
        },
        batchImportVisible: false,
        xlsLoading: false,
        batchImportFileList: [],
        chargingStationResult:[],
        batchImportVisible2:false,
        selectTamplateId:"",
        submitting: false,
        selectYear:"",
        uploadUrlXls: Constant.serverUrl + "/base/personInfo/importXls",
        uploadXlsData: {
            subFolder: "personInfo",
        },
        headers: {
            Authorization: getToken(),
        },
        //上传地址
        uploadUrl: Constant.serverUrl + "/uploadPicture",
        uploadData: {
          subFolder: "fundIncomeInfo",
        },
        fileUrl: "",
        statusList:[
          {
            "id":"0",
            "name":"未认证",
            "value":"0"
          },
          {
            "id":"1",
            "name":"已认证",
            "value":"1"
          }
        ],
      };
    },
    methods: {
      changePage(pageIndex,exportFlag) {
        var self = this;
  
        console.log(pageIndex);
  
        self.pageIndex = pageIndex;
        var formData = new FormData();
  
        formData.append("pageIndex", self.pageIndex);
        
        if(exportFlag!=null){
            formData.append("exportFlag", exportFlag);
            formData.append("pageSize", 10000);
        }
        else{
            formData.append("pageSize", self.pageSize);
        }
        formData.append("year", self.queryModel.year);
        formData.append("title", self.queryModel.title);
  
        self.loading = true;
  
        templateInfoApi.pageList(formData).then(function(response) {
          self.loading = false;
            var jsonData = response.data;
            if(jsonData.result) {
                if(exportFlag){
                    //导出
                    self.$message({
                        showClose: true,
                        type: "success",
                        message: `报表已生成，<a href="${jsonData.data}">请点击链接下载</a>`,
                        dangerouslyUseHTMLString: true,
                        duration: 30000
                    });
                }
                else{
                    //分页查看
                    var page = jsonData.data;

                    self.tableData = page.data;
                    self.totalPages = page.totalPages;
                    self.totalElements = page.recordsTotal;
                }
            }
            else{
                self.$message.warning(jsonData.message);
            }
        }).catch((error)=>{
          self.loading = false;
        });
      },
      pageSizeChange(pageSize) {
        this.pageSize = pageSize;
      },
      sortChange(data) {
        this.field = data.column.field;
        this.direction = data.order == "ascending" ? "asc" : "desc";
  
        this.changePage(this.pageIndex);
      },
      handleSelectionChange(val) {
        this.multipleSelection = val;
      },
      handleReset(name) {
        this.$refs[name].resetFields();
      },
      handleAdd() {
        var self = this;
        
        self.modalTitle = "新增模板";
        self.businessKey = "";
        self.showModal = true;
      },
      handleEdit(record) {
        var self = this;
        
        self.modalTitle = "编辑模板";
        self.businessKey = record.id;
        self.showModal = true;
      },
      handleOption(record){
        var self = this;
        
        self.modalTitle2 = "编辑项目";
        self.businessKey = record.id;
        self.showModal2 = true;
      },
      handleDateRange(record){
        var self = this;
        
        self.modalTitle3 = "编辑日期范围";
        self.businessKey = record.id;
        self.showModal3 = true;
      },
      handleSave(row){
        var self = this;

        var formData = new FormData();

        formData.append("id", row.id);
        formData.append("attachment", row.attachment);

        templateInfoApi.saveAttachment(formData).then(function(response) {
          self.loading = false;
            var jsonData = response.data;
            if(jsonData.result) {
              self.$message({
                message: "保存成功!",
                type: "success",
              });
              self.changePage(self.pageIndex);
            }
            else{
                self.$message.warning(jsonData.message);
            }
        }).catch((error)=>{
          self.loading = false;
        });
      },
      handleChecked(record){
        var self = this;

        this.$confirm("审核后模板不能修改，是否确认审核？", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(() => {
            templateInfoApi.checked(record.id).then(function(response) {
            var jsonData = response.data;
  
            if (jsonData.result) {
              // var index = self.tableData.indexOf(record);
              // self.tableData.splice(index, 1);
              self.changePage(self.pageIndex);
  
              self.$message({
                type: "success",
                message: "审核成功!"
              });
            }
          });
        });
      },
      handleDelete(record) {
        var self = this;
  
        this.$confirm("是否确认删除？", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(() => {
            templateInfoApi.remove(record.id).then(function(response) {
            var jsonData = response.data;
  
            if (jsonData.result) {
              // var index = self.tableData.indexOf(record);
              // self.tableData.splice(index, 1);
              self.changePage(self.pageIndex);
  
              self.$message({
                type: "success",
                message: "删除成功!"
              });
            }
          });
        });
      },
      handleBatchDelete() {
        var self = this;
  
        var idList = this.multipleSelection.map(record => {
          return record.id;
        });
  
        this.$confirm("是否确认删除选中项？", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(() => {
            templateInfoApi.batchRemove(idList).then(function(response) {
            var jsonData = response.data;
  
            if (jsonData.result) {
              self.changePage(self.pageIndex);
  
              self.$message({
                type: "success",
                message: "删除成功!"
              });
            }
          });
        });
      },
      exportXls() {
        this.changePage(1,true);
      },
        onDetailModalClose(refreshed) {
            this.showModal = false;
    
            if(refreshed) {
            this.changePage(this.pageIndex);
            }
        },
        onDetailModalClose2(refreshed) {
            this.showModal2 = false;
    
            if(refreshed) {
            this.changePage(this.pageIndex);
            }
        },
        onDetailModalClose3(refreshed) {
            this.showModal3 = false;
    
            if(refreshed) {
            this.changePage(this.pageIndex);
            }
        },
        beforeUpload(file, fileList) {
            //导入前判断
            var self = this;
            self.xlsLoading = true;
            return true;
        },
        //批量导入-上传成功
        handleBatchImportSuccess(response, file, fileList) {
        var self = this;
        self.xlsLoading = false;

        if (response.result) {
            self.$message.success(response.message);
            this.batchImportFileList = [];
            this.changePage(1);


        } else {
            //this.$message.error(response.message);
            this.batchImportFileList = [];
            this.changePage(1);

            if (response.data != null) {
            //下载有错误信息提示的报表
            //window.open(response.data);
            self.$message({
                showClose: true,
                dangerouslyUseHTMLString: true,
                message:
                response.message +
                `,<a href="${response.data}" target="_blank">点击下载未导入的数据报表</a>&nbsp;`,
                duration: 30000,
            });
            }
        }

        this.batchImportVisible = false;
        },
        //批量导入-预览
        handleBatchImportPreview(file) {
        console.log(file.url);
        },
        //批量导入-移除
        handleBatchImportRemove(file, fileList) {
        console.log(file, fileList);
        },
        //批量导入-移除前操作
        beforeBatchImportRemove(file, fileList) {
        console.log(file, fileList);
        },
        //批量导入-文件超出个数限制时的钩子
        handleBatchImportExceed(files, fileList) {
        this.$message.warning(
            `当前限制选择 3 个文件，本次选择了 ${files.length} 个文件，共选择了 ${
            files.length + fileList.length
            } 个文件`
        );
        },

        handleAvatarSuccess(res, row) {
          row.attachment = res.data;
        },
        beforeAvatarUpload(file) {
          const isLt2M = file.size / 1024 / 1024 < 2;
    
          if (!isLt2M) {
            this.$message.error("上传头像图片大小不能超过 2MB!");
          }
          return isLt2M;
        },
        batchGenerateData(record){
          this.selectTamplateId = record.id;
          this.batchImportVisible2 = true;
        },
        
        handleGenerateData(templateId,year){
          var self = this;
          self.$confirm("生成数据后列表原数据会被覆盖，请谨慎操作！确认生成数据？", "提示", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning"
          }).then(() => {
            var formData = new FormData();

            formData.append("templateId", templateId);

            fundIncomeInfoApi.generateData(formData).then(function(response) {
                var jsonData = response.data;
                if(jsonData.result) {
                  self.changePage(self.pageIndex); 
                  self.$message({
                    type: "success",
                    message: "生成数据成功!"
                  });

                  self.batchImportVisible2 = false
                }
                else{
                    self.$message.warning(jsonData.message);
                }
            }).catch((error)=>{
              self.loading = false;
            });
          });
        },
        isImageFile(url){
          // 获取文件扩展名
          const extension = url.substring(url.lastIndexOf('.') + 1).toLowerCase();
          // 支持的图片扩展名列表
          const imageExtensions = ['jpg', 'jpeg', 'png', 'gif', 'bmp'];
          // 判断当前文件扩展名是否为图片扩展名
          if (imageExtensions.includes(extension)) {
            return true;
          }
          return false;
        },
    },
    mounted: function() {
      var self = this;
      this.changePage(1);
    },
    components: {
        "templateDepartment-detail":templateDepartmentDetail,
        "templateDepartment-edit-date":templateDepartmentEditDate
    }
  };
  </script>
  <style lang="scss" scoped>
  .el-breadcrumb {
    margin: 10px;
    line-height: 20px;
  }
  
  .el-divider {
    margin: 5px 0;
  }
  
  .demo-form-inline {
    margin-left: 10px;
    text-align: left;
  }
  
  .button-group {
    padding: 10px;
    text-align: left;
  }
  </style>