<template>
  <div v-loading.fullscreen.lock="fullscreenLoading">
    <div class="d-flex flex-between">
      <div>
        <el-button type="primary" size="medium" @click="addFWNG">
          <span class="d-in-block v-mid el-icon-plus font-size-16"></span>
          <span class="d-in-block v-mid font-size-16">新建发文拟稿</span>
        </el-button>
        <el-button type="primary" size="medium" @click="addLXMB">
          <span class="d-in-block v-mid el-icon-plus font-size-16"></span>
          <span class="d-in-block v-mid font-size-16">上传类型模版</span>
        </el-button>

        <el-button type="danger" size="medium" @click="batchDel" :disabled="multipleSelection.length == 0">
          <span class="d-in-block v-mid font-size-16">删除</span>
        </el-button>

      </div>
      <el-form label-width="100px" :inline="true">
        <!-- <el-form-item prop="state_value">
          <el-select class="mr10" v-model="type_value" placeholder="请选择类别">
            <el-option v-for="item in type_list" :key="item.value" :label="item.label" :value="item.value"></el-option>
          </el-select>
        </el-form-item> -->
        <el-form-item prop="keyword">
          <el-input placeholder="请输入搜索关键字" v-model="keyword" clearable @clear="getListData"></el-input>
        </el-form-item>
        <el-button type="primary" class="ml5" @click="getListData">搜索</el-button>
      </el-form>
    </div>

    <el-table :data="tableData" tooltip-effect="dark" v-loading="loading" style="width: 100%" @selection-change="handleSelectionChange">
      <el-table-column type="selection" align="center" width="55"></el-table-column>
      <el-table-column label="序号" align="center" type="index" width="50"></el-table-column>
      <el-table-column label="类型" show-overflow-tooltip prop="lb_name"></el-table-column>
      <el-table-column label="上传人" prop="create_user_name"></el-table-column>
      <el-table-column label="上传时间" prop="create_dateline"></el-table-column>
      <el-table-column label="是否启用" >
        <template slot-scope="scope">
          <el-switch v-model="scope.row.lb_status_option_k=='1' ? true : false " @change="switchChange($event,scope.row)"></el-switch>
        </template>
      </el-table-column>
      <el-table-column label="模版状态" >
        <template slot-scope="scope">
          {{scope.row.lb_check_option_k=="1" ? '已确认': '待确认' }}
        </template>
      </el-table-column>
      <el-table-column label="操作" width="200">
        <template slot-scope="scope">
          <el-button type="text" @click="detailShow(scope.row)">详情</el-button>
          <el-button type="text" @click="singleDel(scope.row)" v-show="false">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <footer class="flex-item-none" style="display: flex; justify-content: flex-end; margin-top: 30px">
      <el-pagination background layout="total,prev, pager, next" :page-size="limit" :total="total"
        :current-page.sync="cur_page" @current-change="handleCurrentChange"></el-pagination>
    </footer>

    <!-- dialog弹出-新建发文拟稿 -->
    <el-dialog title="新建发文拟稿" :visible.sync="dialogFormVisible_fwng" width="50%">
      <el-form :model="dialogForm_fwng" label-width="120px" label-position="left"  ref="addForm_fwng" :rules="rules_check_fwng">
        <el-form-item label="类型" prop="lxObj">
          <el-select v-model="dialogForm_fwng.lxObj" placeholder="请选择类型" @change="switchLBData" style="width:100%;" filterable>
             <el-option v-for="item in lxLIST " :key="item.value+ Math.random()" :label="item.label"
              :value="item" >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="标题">
          <el-input v-model="dialogForm_fwng.bt" placeholder="请输入标题"></el-input>
        </el-form-item>
        <el-form-item label="发文字号" prop="fwzh">
          <el-input v-model="dialogForm_fwng.fwzh" placeholder="发文字号自动填充：例如：景教函〔2022〕001号" disabled>
          </el-input>
        </el-form-item>
        <el-form-item label="发起人" prop="fqrObj">
          <el-select v-model="dialogForm_fwng.fqrObj" placeholder="请选择发起人" style="width:100%;" filterable>
            <el-option v-for="item in userLIST " :key="item.value+ Math.random()" :label="item.label"
              :value="item" >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="发起科室" prop="fqksObj">
          <el-select v-model="dialogForm_fwng.fqksObj" placeholder="请选择发起科室" style="width:100%;" filterable  @change="KsLinkLc">
            <el-option v-for="item in orgLIST " :key="item.value+ Math.random()" :label="item.label"
              :value="item" >
            </el-option>
          </el-select>
        </el-form-item>
         <el-form-item label="关联流程" prop="gllcObj">
          <el-select style="width: 100%" v-model="dialogForm_fwng.gllcObj" placeholder="请选择关联流程" filterable >
            <el-option v-for="item in lcglLIST " :key="item.value+ Math.random()" :label="item.label"
              :value="{value:item.value,label:item.label}">
            </el-option>
          </el-select>
        </el-form-item>
         <el-form-item label="正文" prop="zw">
          <!-- <el-input type="textarea" v-model="dialogForm_fwng.zw" placeholder="请输入正文" :rows="6"></el-input> -->
          <Tinymce v-if="dialogFormVisible_fwng" v-model="dialogForm_fwng.zw" :height="300" :key="timestamp"></Tinymce>
        </el-form-item>
        <el-form-item label="附件"  >
          <FileUpload :limit="1" v-if="dialogFormVisible_fwng" :full.sync="dialogForm_fwng.fj" :key="timestamp" >
            <div slot="tip" class="el-upload__tip">
              支持文件类型:doc(.docx)、.ppt(.pptx)、.xls(.xlsx)、.pps、.wps、.pdf、.txt文件格式。
            </div>
          </FileUpload>
        </el-form-item>

      </el-form>
      <div slot="footer">
        <el-button @click="formSubmit_fwng('addForm_fwng','save')">保存</el-button>
        <el-button type="primary" @click="formSubmit_fwng('addForm_fwng','comp')">完成</el-button>
      </div>
    </el-dialog>

    <!-- dialog弹出-上传类型模版 -->
    <el-dialog :title="title" :visible.sync="dialogFormVisible_lxmb" width="600px">
      <el-form :model="dialogForm_lxmb" label-width="120px" label-position="left"  ref="addForm" :rules="rules_check">
        <el-form-item label="项目类别名称" prop="xmlbmc">
          <el-input v-model="dialogForm_lxmb.xmlbmc" ></el-input>
        </el-form-item>
        <el-form-item label="附件" >
           <!--  :on-change="handleChange"-->
          <el-upload
            v-model="dialogForm_lxmb.fj"
            class="upload-demo"
            action="#"
            :http-request="appendixHttpRequest"
            :on-remove="handleRemoveAppendix"
            :limit="1"
            :file-list="appendixList"
            accept=".doc,.docx,.wps"
            >
            <el-button size="small" type="primary">点击上传</el-button>
            <div slot="tip" class="el-upload__tip">支持文件类型:.doc(.docx)、.wps文件格式</div>
          </el-upload>
        </el-form-item>
        <el-form-item label="是否启用" v-show="false">
          <el-switch v-model="dialogForm_lxmb.opneIt"></el-switch>
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button @click="dialogFormVisible_lxmb = false">取 消</el-button>
        <el-button type="primary" @click="formSubmit_LXMB('addForm')">确 定</el-button>
      </div>
    </el-dialog>

    <!--详情dialog 显示-->
    <el-dialog title="详情" :visible.sync="dialogFormVisible_detail">
        <div>
          <iframe  :src="prefixPDFUrl+curFileShowUrl" v-if="curFileShowUrl" style="width:100%;min-height:600px;border:0;"  name="ifrmname" id="ifrmid" ></iframe>
        </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible_detail = false">取 消</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import { fwng_list, fwng_add, fwng_edit, fwng_del, fwng_detail,fwng_lb_list,fwng_lb_add,fwng_lb_edit,fwng_lb_detail,fwng_lb_del,gwglLcgl_List,get_gwzh,org_users,org_list } from "./itemApi";
import { useUserStore } from "@/stores/user";
const { real_name,user_id, dept_ids } = useUserStore();
import FileUpload from "@/components/FileUpload/index.vue";
import Tinymce from "@/components/TinymceWord/index.vue";
export default {
  name: "jblx",
  components: {
    FileUpload,
    Tinymce
  },
  data() {
    const validateLogo = (rule, value, callback) => {
      if (!this.dialogForm_lxmb.fj) {
        callback(new Error('请上传附件'))
      } else {
        callback()
      }
    }
    return {
      fullscreenLoading: false,
      keyword: "",
      tableData: [],
      lxLIST:[],
      userList: [],
      userLIST:[],
      lcglLIST:[],
      orgLIST:[],
      type_value: "",
      type_list: [
        {
          label: "全部",
          value: "0",
        },
        {
          label: "未参与",
          value: "1",
        },
        {
          label: "已参与",
          value: "2",
        },
      ],
      multipleSelection: [],
      limit: 10,
      total: 12,
      cur_page: 1,
      extraParameters:{
        api:'json',
        urltype:2,
      },
      updateUrl:window.globalVariables.api+'upload/main/file',
      dialogFormVisible_fwng: false,
      dialogForm_fwng: {
        lxObj: '',
        bt: '',
        fwzh:'',
        fqrObj: '',
        fqksObj: '',
        gllcObj:'',
        zw: '',
        fj:'',
      },
      rules_check_fwng: {
        lxObj: [
          { required: true, message: '请选择类型', trigger: 'change'}
        ],
        bt: [
          { required: true, message: '请输入标题', trigger: 'blur'}
        ],
        fwzh: [
          { required: true, message: '请规范输入发文字号', trigger: 'blur'}
        ],
        fqrObj: [
          { required: true, message: '请选择发起人', trigger: 'change'}
        ],
        fqksObj: [
          { required: true, message: '请选择发起科室', trigger: 'change'}
        ],
        gllcObj:[
          {required: true, message: '请选择关联科室', trigger: 'change'}
        ],
        zw: [
          { required: true, message: '请输入正文', trigger: 'blur'}
        ],
        fj:[
          { required: true, message: '请上传附件', trigger: 'blur'}
        ]
      },

      appendixList: [],
      dialogFormVisible_lxmb: false,
      dialogForm_lxmb: {
        xmlbmc: '',
        fj:'',
        opneIt:false
      },
      rules_check: {
        xmlbmc: [
          { required: true, message: '请输入项目类别名称', trigger: 'blur'}
        ],
        fj: [
          { required: true, validator: validateLogo, trigger: 'change'}
        ],
      },
      title: "",
      isEdit: false,
      id: "",
      loading: false,

      dialogFormVisible_detail: false,
      detail_form: {
        xmlbmc: '',
        cjr: '',
        cjsj: '',
        sfqy:'',
      },
      formLabelWidth: '120px',
      marDis:false,
      curFileShowUrl:'',
      timestamp: Date.now(),
      prefixPDFUrl:window.globalVariables.api+'/plugins/pdf.js/web/viewer2.html?file=',
    };
  },
  mounted() {
    this.getListData();
  },
  methods: {
    //获取用户列表
    getUserList() {
      let data = {
        dept_id: dept_ids[0],
        page: 1,
        limit: 9999,
      };
      org_users(data).then((res) => {
        if (res.code == 1) {
          this.userList = res.data.page_data;
          this.userLIST = [];
          res.data.page_data.forEach(item => {
            this.userLIST.push({
              label: item.user_realname,
              value:item.user_id,
            })
          })
        }
      });
    },
    //组织机构列表
    orgList() {
      let transObjs = {
        limit: 999,
        uo_pid:'385',
      }
      org_list(transObjs)
        .then(res => {
          if (res.code == "1") {
            let singleData = res.data.page_data;
            singleData.forEach(item => {
              this.orgLIST.push({
                label: item.uo_name,
                value: item.uo_id
              })
            });
          }
        })
        .catch(err => { console.log(err) });
    },
    //初始化列表数据
    getListData() {
      this.loading = true;
      let transObj = {
        page: this.cur_page,
        limit: this.limit,
        keyword: this.keyword,
      };
      fwng_lb_list(transObj).then((res) => {
        this.loading = false;
        if (res.code == "1") {
          this.tableData = res.data.page_data;
          this.cur_page = Number(res.data.page_now);
          this.total = Number(res.data.total_rows);
        }

      });
    },
     //多选
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    //批量删除
    batchDel() {
      let delId = [];
       this.multipleSelection.forEach(item => {
         delId.push(item.lb_id);
      })
      let transObj = {
        lb_id:delId
      }
      this.$confirm("确认删除选中项目?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          fwng_lb_del(transObj).then((res) => {
            if (res.code == 1) {
              this.$message({
                message: res.msg,
                type: "success",
              });
              this.getListData();
            } else {
              this.$message({
                message: res.msg,
                type: "error",
              });
            }
          });
        })
        .catch(() => { });
    },
    //table表格中switch 切换
    switchChange(val, row) {
      //lb_check 1:已确认,2：待确认;
      if (row.lb_check_option_k == '1') {
        this.fullscreenLoading = true;
        let transObj = {
          issubmit:1,
          lb_id: row.lb_id,
          jdbg_gwgl_lxmb: {
            lb_status:val== true ? 1 : 2
          }
        }
        fwng_lb_edit(transObj)
          .then(res => {
            if (res.code == 1) {
              this.fullscreenLoading = false;
              this.$message({
                message: "编辑成功！",
                type: "success",
              });

              this.getListData();
            } else {
              this.$message({
                message: res.msg,
                type: "error",
              });
            }
          })
        .catch(err=>{console.log(err)})
      } else {
        this.$message({
          message: "待确认的模版,无法开启~",
          type: "error",
        })
        return
      }

    },
    //选择类别
    switchLBData(val) {
      let transObj = {
        issubmit:1,
        lb_id: val.value,
      }
      get_gwzh(transObj)
      .then(res => {
        if (res.code == 1) {
          this.dialogForm_fwng.fwzh = res.data.data;
        } else {
          this.$message({
            message: res.msg,
            type: "error",
          });
        }
      })
      .catch(err=>{console.log(err)})

      // switch (val.value) {
      //   case "1"://教育局文件格式-景教〔2022〕X号
      //     this.dialogForm_fwng.fwzhLb = "景教〔2022〕";
      //   break;
      //   case '2'://教育局通知格式-景教通〔2022〕X号
      //     this.dialogForm_fwng.fwzhLb = "景教通〔2022〕";
      //     break;
      //   case '3'://教育局便函格式-景教函〔2022〕X号
      //     this.dialogForm_fwng.fwzhLb = "景教函〔2022〕";
      //   break;
      //   case '4'://教育局工会文件格式-景教工〔2022〕X号
      //     this.dialogForm_fwng.fwzhLb = "景教工〔2022〕";
      //   break;
      //   case '5'://教研室发文格式-景研训〔2022〕X号
      //     this.dialogForm_fwng.fwzhLb = "景教工〔2022〕";
      //   break;
      //   case '6'://机关党委文件格式-景教党〔2022〕X号
      //     this.dialogForm_fwng.fwzhLb = "景教工〔2022〕";
      //   break;
      // }
    },
    //新建发文拟稿-dialog
    addFWNG() {
      this.lbList();
      // this.getUserList();
      this.orgList();
      this.userLIST = [{ label: real_name, value: user_id }];
      this.dialogForm_fwng = {
        lxObj: '',
        bt: '',
        fwzh:'',
        fqrObj: {label:real_name,value:user_id},
        fqksObj: '',
        gllcObj:'',
        zw: '',
        fj: '',
      };
      this.dialogFormVisible_fwng = true;
    },
    //发文拟稿_保存
    formSubmit_fwng(formName,marklabel) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          let transObj={
            issubmit: 1,
            jdbg_gwgl_gw: {
              lb_name: this.dialogForm_fwng.lxObj.label,//类别名称
              lb_id:this.dialogForm_fwng.lxObj.value,//类别id
              gw_title: this.dialogForm_fwng.bt,// 公文名称

              // gw_zh_header:this.dialogForm_fwng.fwzhLb,
              // gw_zh_behide:this.dialogForm_fwng.fwzh,
              gw_zh:this.dialogForm_fwng.fwzh,//发文字号(拼合)

              gw_fqr_name: this.dialogForm_fwng.fqrObj.label,//发起人姓名
              gw_fqks_name: this.dialogForm_fwng.fqksObj.label,//发起科室名称
              gw_fqks_id: this.dialogForm_fwng.fqksObj.value,//发起科室id
              gw_content: this.dialogForm_fwng.zw,//正文
              gw_fj: this.dialogForm_fwng.fj,//公文附件
              lc_id:this.dialogForm_fwng.gllcObj.value,
            }
          }
          fwng_add(transObj)
          .then(res => {
            if (res.code == "1") {
              if (marklabel == "save") {//存为草稿
                this.$message({
                  message: res.msg,
                  type: "success",
                });
                this.getListData()
              } else {//完成提交
                let transData = res.data.one_info;
                this.finishNG(transData);
              }
              this.dialogFormVisible_fwng = false;
            } else {
              this.$message({
                  message: res.msg,
                  type: "error",
                });
            }
          })
          .catch(err=>{console.log(err)})
        }
      })
    },
    //发文拟稿-完成-指的是直接提交
    finishNG(item) {
      //先提交到后台
      let transObj = {
        issubmit: 1,
        gw_id: item.gw_id,
        jdbg_gwgl_gw: {
          gw_status: 2
        }
      }
      fwng_edit(transObj)
        .then(res => {
          if (res.code == "1") {
            this.$message({
              message: res.msg,
              type: "success",
            });
            this.getListData();
          } else {
            this.$message({
              message: res.msg,
              type: "error",
            });
          }
        })
        .catch(err => { console.log(err) })
    },
    //点击科室找流程
    KsLinkLc(val) {
      let transObjs = {
        public:1,
        lc_status: 1,
        lc_yydx:val.value,
        lc_yydx_name:val.label,
      }
      gwglLcgl_List(transObjs)
        .then(res => {
          let singleData = res.data.page_data;
          this.lcglLIST = [];
          singleData.forEach(item => {
            this.lcglLIST.push({
              label: item.lc_name,
              value: item.lc_id
            })
          })
        })
        .catch(err => { console.log(err) });
    },
    //上传类型模版-dialog
    addLXMB() {
      this.title = "上传类型模版";
      this.appendixList=[];
      this.dialogForm_lxmb = {
        xmlbmc: '',
        fj: '',
        opneIt:false
      };
      this.isEdit = false;
      this.dialogFormVisible_lxmb = true;
    },
    //类型模版_提交
    formSubmit_LXMB(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          let transObj = {
            issubmit: 1,
            jdbg_gwgl_lxmb: {
              create_user_name:real_name,//创建用户名
              lb_name: this.dialogForm_lxmb.xmlbmc,//名称
              lb_status: this.dialogForm_lxmb.opneIt== true ? 1 : 2,//是否启用1-启用 2-不启用
              lb_file:this.dialogForm_lxmb.fj[0].url,
            }
          };
          console.log(transObj,"0000")
          if (!this.isEdit) {
            fwng_lb_add(transObj).then((res) => {
              if (res.code == 1) {
                this.$message({
                  message: res.msg,
                  type: "success",
                });
                this.getListData()
                this.dialogFormVisible_lxmb = false;
              } else {
                this.$message({
                  message: res.msg,
                  type: "error",
                });
              }
            });
          } else {
            transObj.lb_id = this.id;
            xmlb_edit(transObj).then((res) => {
              if (res.code == 1) {
                this.$message({
                  message: "编辑成功！",
                  type: "success",
                });

                this.dialogFormVisible_lxmb = false;
                this.getListData();
              } else {
                this.$message({
                  message: res.msg,
                  type: "error",
                });
              }
            });
          }

        }
      })

    },
    //编辑
    editData(item) {
      this.title = "编辑设置";
      this.isEdit = true;
      this.id = item.lb_id;
      let transObj = {
        lb_id:item.lb_id
      }
      xmlb_detail(transObj)
        .then(res => {
          if (res.code == "1") {
            let singleData=res.data.one_info;
            this.dialogForm= {
              xmlbmc: singleData.lb_name,
              opneIt: singleData.lb_status == '1' ? true : false,
            };
          }
        })
        .catch(err => { console.log(err) });

      this.dialogFormVisible_lxmb = true;
    },
    //详情
    detailShow(item) {
      // this.curFileShowUrl = item.online_file;
      let lbCheck = item.lb_check_option_k;
      this.curFileShowUrl = item.lb_file_pdf;
      if (lbCheck == '2') {
        this.$message({
          message: "模版正在审核中~",
          type: "error",
        })
        return
      } else {
        this.dialogFormVisible_detail = true;
      }

    },
     //删除
    singleDel(item) {
      let transObj = {
        lb_id:item.lb_id
      }
      fwng_lb_del(transObj)
      .then(res=>{
        if(res.code=="1"){
          this.$message({
            message: res.msg,
            type: "success",
          });
          this.getListData()
        }
      })
      .catch(err=>{console.log(err)})
    },
    /**附件上传网络请求*/
    appendixHttpRequest(param){
      const { token } = useUserStore()
      let file=param.file;
      let formData = new FormData();
      formData.append('filedata', file)
      formData.append('api',this.extraParameters.api)
      formData.append('urltype',this.extraParameters.urltype)
      formData.append('token',token);
      //发起axios请求
      let that=this;
      that.$axios({
        method: 'post',
        url: this.updateUrl,
        headers:{'Content-Type': 'multipart/form-data'},
        data: formData
      })
      .then(res=>{
      var response=res.data;
      if(response.code=="1"){//单个上传后台返回的是相对地址
      let tempArr={
        name:response.data.file_name,
        url:response.data.url
      }
      //存入appendixList列表中
        this.appendixList.push(tempArr);
        this.dialogForm_lxmb.fj = this.appendixList;
        this.$message({
        message: response.msg,
        type: 'success'
        })
      }
      })
      .catch(error=>{
      console.log(error)
      })

    },
     /**文件上传 暂时未启用*/
    handleChange(file, fileList) {
      console.log("0909")
      //限制文件大小
      if(file.size/1024/1024>5){
      this.$message({
        message: '文件大小不能超过5M',
        type: 'error'
      })
      return false;
      }

      // 开始上传
      const { token } = useUserStore();
      let formData=new FormData();
      formData.append('api','json');
      formData.append('token',token);
      formData.append('filedata',file.raw);

      let that=this;
      that.$axios({
      method: 'post',
      url: this.updateUrl,
      headers:{'Content-Type': 'multipart/form-data'},
      data: formData
      })
      .then(res=>{
      var response=res.data;
      if(response.code=="1"){//单个上传后台返回的是相对地址
      let tempArr={
        name:response.data.file_name,
        url:response.data.url
      }

      //存入appendixList列表中
      this.appendixList.push(tempArr);
        this.$message({
        message: response.msg,
        type: 'success'
        })
      }

      }).catch(error=>{
      console.log(error);
      })
    },
    /**附件删除*/
    handleRemoveAppendix(file, fileList) {
      console.log(file, fileList);
      var fileName=file.name;
      this.appendixList=this.appendixList.filter(item => item.name !== fileName);
    },
    //翻页
    handleCurrentChange(val) {
      this.cur_page = val;
      this.getListData();
    },
    //开启的类别
    lbList() {
      let transObj = {
        lb_status:1
      };
      fwng_lb_list(transObj).then((res) => {
        if (res.code == "1") {
          this.lxLIST = [];
          res.data.page_data.forEach(item => {
            this.lxLIST.push({
              label: item.lb_name,
              value: item.lb_id
            })
          });
        }
      });
    },

  },

};
</script>

<style lang="scss" scoped>
.time-type-list {
  width: 100%;
  border-bottom: 1px solid #f3f3f3;
  margin-bottom: 20px;
  display: flex;

  li {
    position: relative;
    top: 2px;
    cursor: pointer;
    width: 50px;
    font-size: 14px;
    line-height: 30px;
    text-align: center;

    &+li {
      margin-left: 20px;
    }

    &.selected {
      color: #265cd4;
      border-bottom: 2px solid #265cd4;
    }
  }
}
</style>
