<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item :label="$t('年份')" prop="year">
        <el-date-picker clearable size="small" style="width: 200px"
                        v-model="queryParams.year"
                        type="year"
                        value-format="yyyy"
                        :placeholder="$t('请选择')+$t('年份')">
        </el-date-picker>
      </el-form-item>
      <el-form-item>
	    <el-button type="cyan" icon="el-icon-search" size="mini" @click="handleQuery">{{ $t('搜索') }}</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">{{ $t('重置') }}</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['plant:targetlist:add']"
        >{{ $t('新增') }}</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="info"
          icon="el-icon-upload2"
          size="mini"
          @click="handleImport"
          v-hasPermi="['plant:targetlist:edit']"
        >{{ $t('导入') }}</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['plant:targetlist:export']"
        >{{ $t('导出') }}</el-button>
        <el-col :span="1.5">
          <el-button
            type="success"
            icon="el-icon-tickets"
            size="mini"
            @click="handleCompany"
          >{{ $t('公司目标') }}</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="success"
            icon="el-icon-tickets"
            size="mini"
            @click="handleCB"
          >{{ $t('事业部目标') }}</el-button>
        </el-col>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="targetlistList"
      row-key="id"
      default-expand-all
      :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
    >
      <el-table-column :label="$t('装置名称')" align="center" prop="plantCode" :formatter="plantCodeFormat" />
      <el-table-column label="ITEM" align="center" prop="item" />
      <el-table-column :label="$t('内容')" align="center" prop="description" />
      <el-table-column :label="$t('目标')" align="center" prop="targets" />
      <el-table-column :label="$t('年份')" align="center" prop="year" />
      <el-table-column :label="$t('备注')" align="center" prop="remarks" :show-overflow-tooltip="true"/>
      <el-table-column :label="$t('操作')" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['plant:targetlist:edit']"
          >{{ $t('修改') }}</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['plant:targetlist:remove']"
          >{{ $t('删除') }}</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-plus"
            @click="handleAddItem(scope.row)"
            v-hasPermi="['plant:targetlist:add']"
            v-if="scope.row.parentId === 0"
          >{{ $t('新增') }}</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 添加或修改目标录入对话框 -->
    <el-dialog v-dialogDrag :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item :label="$t('装置名称')" prop="plantCode">
          <el-select v-model="form.plantCode" :placeholder="$t('请选择') + $t('装置名称')">
            <el-option
              v-for="dict in plantCodeOptions"
              :key="dict.dictValue"
              :label="dict.dictLabel"
              :value="dict.dictValue"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="ITEM" prop="item">
          <el-input v-model="form.item" :placeholder="$t('请输入') + 'ITEM'" />
        </el-form-item>
        <el-form-item :label="$t('内容')" prop="description">
          <el-input v-model="form.description" :placeholder="$t('请输入') + $t('内容')" />
        </el-form-item>
        <el-form-item :label="$t('目标')" prop="targets">
          <el-input v-model="form.targets" :placeholder="$t('请输入') + $t('目标')" />
        </el-form-item>
        <el-form-item :label="$t('年份')" prop="year">
          <el-input v-model="form.year" :placeholder="$t('请输入') + $t('年份')" />
        </el-form-item>
        <el-form-item :label="$t('备注')" prop="remarks">
          <el-input v-model="form.remarks" :placeholder="$t('请输入') + $t('备注')" />
        </el-form-item>
        <el-form-item :label="$t('备注')" prop="yardstick" v-if="form.parentId !== 0">
          <el-input v-model="form.yardstick" :placeholder="$t('请输入') + $t('判断标准')" />
        </el-form-item>
        <el-form-item :label="$t('合作者')" prop="partners" v-if="form.parentId !== 0">
          <el-select v-model="form.partners" :placeholder="$t('请选择') + $t('合作者')" multiple>
            <el-option
              v-for="dict in partnersOptions"
              :key="dict.dictValue"
              :label="dict.dictLabel"
              :value="dict.dictValue"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item :label="$t('归属部门')" prop="deptId">
          <treeselect v-model="form.deptId" :options="deptOptions" :show-count="true" :placeholder="$t('请选择') + $t('归属部门')" />
        </el-form-item>
        <el-form-item :label="$t('父级目录')" prop="parentId">
          <treeselect v-model="form.parentId" :options="targetlistOptions" :normalizer="normalizer" :placeholder="$t('请选择') + $t('父级目录')" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">{{ $t('确 定') }}</el-button>
        <el-button @click="cancel">{{ $t('取 消') }}</el-button>
      </div>
    </el-dialog>
    <!-- 公司目标对话框 -->
    <el-dialog v-dialogDrag :title="target.title" :visible.sync="target.open" width="700px" append-to-body>
      <el-upload
        ref="target"
        :limit="50"
        :headers="target.headers"
        :action="target.url + '?pType=' + target.pType + '&pId=' + target.pId"
        :disabled="target.isUploading"
        :on-progress="handleFileDocProgress"
        :on-success="handleFileDocSuccess"
        :auto-upload="true"
        drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">
          {{ $t('将文件拖到此处，或') }}
          <em>{{ $t('点击上传') }}</em>
        </div>
      </el-upload>
      <el-table :data="target.commonfileList" border>
        <el-table-column :label="$t('文件名')" align="center" prop="fileName" :show-overflow-tooltip="true">
          <template slot-scope="scope">
            <a  class="link-type"  @click="handleDownload(scope.row)">
              <span>{{ scope.row.fileName }}</span>
            </a>
          </template>
        </el-table-column>
        <el-table-column :label="$t('大小(Kb)')" align="center" prop="fileSize" :show-overflow-tooltip="true" width="80" />
        <el-table-column :label="$t('上传人')" align="center" prop="creator" :show-overflow-tooltip="true" width="120"/>
        <el-table-column :label="$t('操作')" align="center" width="150" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <el-button
              v-if="scope.row.fileName.endsWith('pdf')"
              size="mini"
              type="text"
              icon="el-icon-view"
              @click="handleSee(scope.row)"
            >{{ $t('预览') }}</el-button>
            <el-button
              size="mini"
              type="text"
              icon="el-icon-download"
              @click="handleDownload(scope.row)"
            >{{ $t('下载') }}</el-button>
            <el-button
              size="mini"
              type="text"
              icon="el-icon-delete"
              @click="handleDeleteDoc(scope.row)"
            >{{ $t('删除') }}</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-dialog v-dialogDrag :title="pdf.title" :visible.sync="pdf.open" width="1700px" append-to-body>
        <div style="margin-top: -60px;float: right;margin-right: 40px;">
          <el-button size="mini" type="text" @click="openPdf">{{$t('新页面打开PDF')}}</el-button></div>
        <div style="margin-top: -30px">
          <iframe :src="pdf.pdfUrl" frameborder="0" width="100%" height="700px"></iframe>
        </div>
      </el-dialog>
      <div slot="footer" class="dialog-footer">
        <!--        <el-button type="primary" @click="submitFileForm">{{ $t('确 定') }}</el-button>-->
        <el-button @click="target.open = false">{{ $t('返 回') }}</el-button>
      </div>
    </el-dialog>
    <!-- 用户导入对话框 -->
    <el-dialog v-dialogDrag :title="upload.title" :visible.sync="upload.open" width="400px" append-to-body>
      <el-upload
        ref="upload"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="upload.headers"
        :action="upload.url"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">
          {{ $t('将文件拖到此处，或') }}
          <em>{{ $t('点击上传') }}</em>
        </div>
        <div class="el-upload__tip" slot="tip">
          <!--<el-checkbox v-model="upload.updateSupport" />是否更新已经存在的用户数据-->
          <el-link type="info" style="font-size:12px" @click="importTemplate">{{ $t('下载模板') }}</el-link>
        </div>
        <form ref="downloadFileForm" :action="upload.downloadAction" target="FORMSUBMIT">
          <input name="type" :value="upload.type" hidden />
        </form>
        <div class="el-upload__tip" style="color:red" slot="tip">{{ $t('提示：仅允许导入“xls”或“xlsx”格式文件！') }}</div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">{{ $t('确 定') }}</el-button>
        <el-button @click="upload.open = false">{{ $t('取 消') }}</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listTargetlist, getTargetlist, delTargetlist, addTargetlist, updateTargetlist, exportTargetlist } from "@/api/plant/targetlist";
import { allFileList, listCommonfile, getCommonfile, delCommonfile, addCommonfile, updateCommonfile, exportCommonfile} from "@/api/common/commonfile";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import { getToken } from "@/utils/auth";
import { treeselect } from "@/api/system/dept";

export default {
  name: "Targetlist",
  components: {
    Treeselect
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 显示搜索条件
      showSearch: false,
      // 目标录入表格数据
      targetlistList: [],
      // 目标录入树选项
      targetlistOptions: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 装置名称字典
      plantCodeOptions: [],
      // 合作者字典
      partnersOptions: [],
      // 用户导入参数
      upload: {
        downloadAction: process.env.VUE_APP_BASE_API + '/common/template',
        //下载模板类型
        type: "targetlist",
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/plant/targetlist/importData"
      },
      //公司目标导入参数
      target: {
        file: "",
        // 是否显示弹出层（公司目标）
        open: false,
        // 弹出层标题（公司目标）
        title: this.$t('公司目标'),
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/common/commonfile/uploadFile",
        commonfileList: null,
        queryParams: {
          pId: 0,
          pType: 'targetCompany'
        },
        //上传类型
        pType: 'targetCompany',
        pId: 0
      },
      pdf : {
        title: '',
        pdfUrl: '',
        numPages: null,
        open: false,
        pageNum: 1,
        pageTotalNum: 1,
        loadedRatio: 0,
      },
      // 部门树选项
      deptOptions: undefined,
      clientHeight:300,
      // 查询参数
      queryParams: {
        item: null,
        description: null,
        targets: null,
        year: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        id: [
          { required: true, message: this.$t('唯一标识id') + this.$t('不能为空'), trigger: "blur" }
        ],
        plantCode: [
          { required: true, message: this.$t('装置名称') + this.$t('不能为空'), trigger: "change" }
        ],
        item: [
          { required: true, message: this.$t('序号') + this.$t('不能为空'), trigger: "blur" }
        ],
        deptId: [
          { required: true, message: this.$t('部门编号') +this.$t('不能为空'), trigger: "blur" }
        ],
      }
    };
  },
  watch: {
    // 根据名称筛选部门树
    deptName(val) {
      this.$refs.tree.filter(val);
    }
  },
  created() {
    this.getList();
    this.getDeptTreeselect();
    this.getDicts("PLANT_DIVIDE").then(response => {
      this.plantCodeOptions = response.data;
    });
    this.getDicts("PARTNERS").then(response => {
      this.partnersOptions = response.data;
    });
  },
  methods: {
    /** 查询目标录入列表 */
    getList() {
      this.loading = true;
      listTargetlist(this.queryParams).then(response => {
        this.targetlistList = this.handleTree(response.data, "id", "parentId");
        this.loading = false;
      });
    },
    /** 查询部门下拉树结构 */
    getDeptTreeselect() {
      treeselect().then(response => {
        this.deptOptions = response.data;
      });
    },
    /** 转换目标录入数据结构 */
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.id,
        label: node.year + "-" + node.item,
        children: node.children
      };
    },
	/** 查询部门下拉树结构 */
    getTreeselect() {
      listTargetlist().then(response => {
        this.targetlistOptions = [];
        const data = { id: 0, item: this.$t('顶级节点'), children: [], year: "" };
        data.children = this.handleTree(response.data, "id", "parentId");
        this.targetlistOptions.push(data);
      });
    },
    // 装置名称字典翻译
    plantCodeFormat(row, column) {
      return this.selectDictLabel(this.plantCodeOptions, row.plantCode);
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        plantCode: null,
        item: null,
        description: null,
        targets: null,
        year: null,
        yardstick: null,
        partners: null,
        delFlag: null,
        createrCode: null,
        createdate: null,
        updaterCode: null,
        updatedate: null,
        deptId: null,
        remarks: null,
        parentId: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
	    this.getTreeselect();
      this.open = true;
      this.title = this.$t('新增') + " " + this.$t('目标录入');
    },
    /** 条目新增按钮操作 */
    handleAddItem(row) {
      this.reset();
      this.getTreeselect();
      this.form.parentId = row.id
      this.open = true;
      this.title = this.$t('新增') + " " + this.$t('目标录入');
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
	    this.getTreeselect();
      if (row != null) {
        this.form.parentId = row.id;
      }
      getTargetlist(row.id).then(response => {
        this.form = response.data;
        let partners = null;
        if (this.form.partners != null) {
          partners = this.form.partners.split(",");
        }
        this.form.partners = partners;
        this.open = true;
        this.title = this.$t('修改') + this.$t('目标录入');
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.parentId !== 0) {
            var partner = null;
            this.form.partners.forEach(function (value,key,arr) {
              if (key != 0) {
                partner = partner + "," + value;
              }else if (key == 0) {
                partner = value;
              }
            })
            this.form.partners = partner;
          }
          if (this.form.id != null) {
            updateTargetlist(this.form).then(response => {
              this.msgSuccess(this.$t('修改成功'));
              this.open = false;
              this.getList();
            });
          } else {
            addTargetlist(this.form).then(response => {
              this.msgSuccess(this.$t('新增成功'));
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      this.$confirm(this.$t('是否确认删除目标录入编号为"') + row.id + this.$t('"的数据项?'), this.$t('警告'), {
          confirmButtonText: this.$t('确定'),
          cancelButtonText: this.$t('取消'),
          type: "warning"
        }).then(function() {
          return delTargetlist(row.id);
        }).then(() => {
          this.getList();
          this.msgSuccess(this.$t('删除成功'));
        })
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm(this.$t('是否确认导出所有目标录入数据项?'), this.$t('警告'), {
        confirmButtonText: this.$t('确定'),
        cancelButtonText: this.$t('取消'),
        type: "warning"
      }).then(function() {
        return exportTargetlist(queryParams);
      }).then(response => {
        this.download(response.msg);
      })
    },
    /** 导入按钮操作 */
    handleImport() {
      this.upload.title = this.$t('用户导入');
      this.upload.open = true;
    },
    /** 公司目标按钮操作 */
    handleCompany() {
      this.target.title = this.$t('公司目标');
      this.target.pType = "company";
      this.target.queryParams.pType = "company";
      this.target.pId = "0";
      this.target.queryParams.pId = "0";
      this.target.open = true;
      this.getFileList()
      this.$nextTick(() => {
        this.$refs.target.clearFiles()
      })
    },
    /** 事业部目标按钮操作 */
    handleCB() {
      this.target.title = this.$t('事业部目标');
      this.target.pType = "cb";
      this.target.queryParams.pType = "cb";
      this.target.pId = "0";
      this.target.queryParams.pId = "0";
      this.target.open = true;
      this.getFileList()
      this.$nextTick(() => {
        this.$refs.target.clearFiles()
      })
    },
    getFileList (){
      allFileList(this.target.queryParams).then(response => {
        this.target.commonfileList = response;
      });
    },
    //附件上传中处理
    handleFileDocProgress(event, file, fileList) {
      this.target.file = file;
      this.target.isUploading = true;
    },
    //附件上传成功处理
    handleFileDocSuccess(response, file, fileList) {
      this.target.isUploading = false;
      this.$alert(response.msg, this.$t('导入结果'), { dangerouslyUseHTMLString: true });
      this.getFileList()
    },
    /** 删除按钮操作 */
    handleDeleteDoc(row) {
      const ids = row.id || this.ids;
      this.$confirm(this.$t('是否确认删除?'), this.$t('警告'), {
        confirmButtonText: this.$t('确定'),
        cancelButtonText: this.$t('取消'),
        type: "warning"
      }).then(function() {
        return delCommonfile(ids);
      }).then(() => {
        this.getList()
        this.msgSuccess(this.$t('删除成功'));
      })
    },
    /** 下载模板操作 */
    importTemplate() {
      this.$refs['downloadFileForm'].submit()
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      if (response.data[0] != null) {
        this.$alert(this.$t('成功导入') + response.msg + this.$t('条数据') + "，" + this.$t('第') + response.data + this.$t('行数据出现错误导入失败')+"。", this.$t('导入结果'), { dangerouslyUseHTMLString: true });
      }else {
        this.$alert(this.$t('成功导入') + response.msg + this.$t('条数据'), this.$t('导入结果'), { dangerouslyUseHTMLString: true });
      }
      this.getList();
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit();
    },
    // 文件下载处理
    handleDownload(row) {
      var name = row.fileName;
      var url = row.fileUrl;
      var suffix = url.substring(url.lastIndexOf("."), url.length);
      const a = document.createElement('a')
      a.setAttribute('download', name)
      a.setAttribute('target', '_blank')
      a.setAttribute('href', process.env.VUE_APP_BASE_API + url)
      a.click()
    },
    openPdf(){
        window.open(this.pdf.pdfUrl);//path是文件的全路径地址
      },
      handleSee (row){
      // window.open(process.env.VUE_APP_BASE_API +'/pdf/web/viewer.html?file=' + process.env.VUE_APP_BASE_API + row.fileUrl);//path是文件的全路径地址
      this.pdf.open =true
      this.pdf.title = row.fileName
      this.pdf.pdfUrl = process.env.VUE_APP_BASE_API +'/pdf/web/viewer.html?file=' + process.env.VUE_APP_BASE_API + row.fileUrl
    }
  }
};
</script>
