<template>
  <div class="app-container">
    <el-form ref="form" :model="form" :rules="rules" label-width="130px" border>
      <table width="100%" border="1">
        <tr style="height: 80px">
          <td colspan="2"><p class="title">发文起草</p></td>
        </tr>

        <!--<tr>
          <td>
            <el-form-item label="机关待字" prop="senderName">
              <el-select v-model="form.officeNumber" placeholder="请选择">
                <el-option label="001" value=""></el-option>
                <el-option label="002" value=""></el-option>
              </el-select>
            </el-form-item>
          </td>
          <td>
            <el-form-item label="文号" prop="number">
            +
            <el-input v-model="form.number" placeholder="请输入发件人-账号" />
          </el-form-item>
          </td>
        </tr>-->
        <tr>
          <td>
            <el-form-item label="缓急" prop="ponderance">
              <el-select v-model="form.ponderance" placeholder="请选择">
                <el-option label="一般" value="4"></el-option>
                <el-option label="平急" value="3"></el-option>
                <el-option label="加急" value="2"></el-option>
                <el-option label="特急" value="1"></el-option>
                <el-option label="特提" value="0"></el-option>
              </el-select>
            </el-form-item>
          </td>
          <td>
            <el-form-item label="密级" prop="securityClass">
              <el-select v-model="form.securityClass" placeholder="请选择">
                <el-option label="一般" value="3"></el-option>
                <el-option label="秘密" value="2"></el-option>
                <el-option label="机密" value="1"></el-option>
                <el-option label="绝密" value="0"></el-option>
              </el-select>
            </el-form-item>
          </td>
        </tr>

        <tr>
          <td colspan="2">
            <el-form-item label="标题：" prop="fwtitle">
              <el-input v-model="form.fwtitle" type="text" placeholder=""/>
            </el-form-item>
          </td>
        </tr>

        <!--园林局样式-->
        <tr>
          <td colspan="2">
            <el-form-item label="发文字号：" prop="fwtitle">
              <el-input v-model="form.referenceNumber" type="text" placeholder=""/>
            </el-form-item>
          </td>
        </tr>
        <!--<tr>
          <td colspan="2">
            <el-form-item label="部门：" prop="fwdept">
              &lt;!&ndash;              <el-input v-model="form.fwdept"  type="text" placeholder=""/>&ndash;&gt;
              <el-input title="选择发文部门" v-model="form.fwdept" placeholder="请选择发文部门" prop="avtiveSend" :disabled="true">
                <template slot="append">
                  <el-button
                    type="primary"
                    icon="el-icon-plus"
                    size="mini"
                    @click="handleSelectDept">
                    选择发文部门
                  </el-button>
                </template>
              </el-input>
            </el-form-item>
          </td>
        </tr>
        <tr>
          <td colspan="2">
            <el-form-item label="主送：" :disabled="true" prop="avtiveSend">
              <el-input v-model="form.avtiveSend" placeholder="请选择主送人"  :disabled="true">
                <template slot="append">
                  <el-button
                    type="primary"
                    icon="el-icon-plus"
                    size="mini"
                    @click="handleSelect(0)">
                    选择主送部门
                  </el-button>
                </template>
              </el-input>
            </el-form-item>
          </td>
        </tr>
        <tr>
          <td colspan="2">
            <el-form-item label=" 抄送：" :disabled="true"  prop="copyTo" >
              <el-input v-model="form.copyTo" placeholder="请选择抄送人":disabled="true">
                <template slot="append">
                  <el-button
                    type="primary"
                    icon="el-icon-plus"
                    size="mini"
                    @click="handleSelect(1)">
                    选择抄送部门
                  </el-button>
                </template>
              </el-input>
            </el-form-item>
          </td>
        </tr>-->
        <tr>
          <td colspan="2">
            <el-form-item label="上传附件：" prop="accessory">
              <el-upload

                accept=".jpg, .png"
                :action="upload.url"
                :headers="upload.headers"
                :file-list="upload.oldFileList"
                multiple
                :show-file-list="true"
                :on-progress="handleFileUploadProgress"
                :on-preview="handlePreview"
                :http-request="submitUpload"
                :on-remove="handleRemove"
                :before-remove="beforeRemove"
              >
                <el-button slot="trigger" size="small" :loading="upload.isUploading"  type="primary">上传文件</el-button>
                <!--                <el-button style="margin-left: 10px;" size="small" type="success" :loading="upload.isUploading" @click="submitUpload">上传文件</el-button>-->
                <div slot="tip" class="el-upload__tip">上传文件大小不超过1M</div>
              </el-upload>
              <ul v-show="!!upload.oldFileList.length" class="old-file-list"></ul>
            </el-form-item>
          </td>
        </tr>
        <tr>
          <td colspan="2">
            <el-form-item label="正文：" prop="content">
              <el-button size="small" type="primary" @click="openIweboffice" v-loading.fullscreen.lock="fullscreenLoading">读取正文</el-button>
              <!--              <el-input v-model="form.content" type="primary" placeholder=""/>-->
            </el-form-item>
          </td>
        </tr>
        <tr>
          <td colspan="2">
            <el-form-item label="接收人员：" :disabled="true">
              <el-input v-model="form.sendUserRealName" placeholder=" 请选择接收人员"
                        :disabled="true">
                <template slot="append">
                  <el-button
                    type="primary"
                    icon="el-icon-plus"
                    size="mini"
                    @click="handleSelect()">
                    选择人员
                  </el-button>
                </template>
              </el-input>
            </el-form-item>
          </td>
        </tr>
        <tr v-show="false">
          <td>
            <el-form-item label="actkey：" prop="actkey">
              <el-input v-model="form.actkey" type="textarea" placeholder=""/>
            </el-form-item>
          </td>

        </tr>


      </table>
    </el-form>
    <div slot="footer" class="dialog-footer" v-show="open3">
      <el-button type="primary" @click="submitForm(1)">提交</el-button>
      <!--      <el-button type="primary" @click="submitForm(0)">保存草稿</el-button>-->
      <el-button @click="cancel">取 消</el-button>
    </div>
    <div slot="footer" class="dialog-footer" v-show="open4">
      <el-button type="primary" @click="submitToDo()">同意</el-button>
      <el-button type="primary" @click="deleteToDo()">拒绝</el-button>
      <el-button @click="cancel">取 消</el-button>
    </div>
    <el-dialog id="content" title="正文"
               :visible.sync="contentOpen"
               :before-close="cancel1" append-to-body
               width="80%"
               top="10"

               height="900px">
      <!-- 动态引入组件-->
      <i-web-office :key="timer" v-if="contentOpen" ref="ioffice" @func="getcontent" :fileData="fileData" ></i-web-office>
      <span slot="footer" class="dialog-footer">
        <el-button @click="contentOpen = false">取 消</el-button>
      </span>
    </el-dialog>
    <select-user-by-dept ref="selectUserByDept" :title="title" :open="Renopen"
                         :inputName="form.sendUserRealName"
                         :inputAccount="form.sendUser"
                         @ok="selectOK"/>


    <el-dialog :title="title" :visible.sync="deptOpen" width="40%" append-to-body style="size: 30px">
      <el-tree
        :data="deptOptions"
        show-checkbox
        default-expand-all
        ref="dept"
        node-key="id"
        empty-text="加载中，请稍后"
        :props="defaultProps"
      ></el-tree>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="getDeptAllCheckedKeys">确 定</el-button>
        <el-button @click="cancelDept">取 消</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
  import SelectUserByDept from "@/components/SelectRen/selectUserByDept";
  import iWebOffice from "./iWebOffice";
  import SelectRen from '@/components/SelectRen';
  import {treeselect} from "@/api/system/dept";
  import {submitYljApply, getFormData, deleteToDoItem, submitToDoItem,updateInfo,uploadFujian} from "@/api/activiti/form/fw";
  import Treeselect from "@riophae/vue-treeselect";
  import {getToken} from "@/utils/auth";

  export default {

    components: {
      SelectUserByDept, iWebOffice, SelectRen,
      Treeselect,
    },

    props: {
      data: '',
      actOpen: false,
    },
    data() {
      return {
        Renopen: false,
        receiverName: [],
        timer: '',
        contentOpen: false,
        receiverAccount: [],
        dialogTableVisible: false,
        fullscreenLoading: false,
        //正文的文件地址
        fileData: {
          filePath: '/profile/doc/NewCreate.doc',
          user: 'xxx',
          EditType: '1',
        },
        fileList3: [],
        // 选中数组
        ids: [],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 总条数
        total: 0,
        // 【请填写功能名称】表格数据
        infoList: [],
        // 弹出层标题
        title: "",
        // 是否显示弹出层
        open: false,
        open1: false,
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          status: undefined,
          deleteTime: undefined
        },
        form: {
          actkey: '',
          content: '',
          fwdept: '',
          ponderance: '',
          securityClass: '',
          referenceNumber:'',
          copyTo: '',
          accessory: '',
          avtiveSend: '',
          sendUserRealName: '',
          sendUser: '',
        },  // 表单参数
        flg: '',
        // 表单校验
        rules: {
          fwtitle: [
            { required: true, message: "标题题不能为空", trigger: "blur" }
          ],
          referenceNumber: [
            { required: true, message: "发文字号不能为空", trigger: "blur" }
          ],
         /* fwdept: [
            { required: true, message: "请选择发文部门", trigger: "blur" }
          ],
          copyTo: [
            { required: true, message: "请选择抄送部门", trigger: "blur" }
          ],
          avtiveSend: [
            { required: true, message: "请选择主送部门", trigger: "blur" }
          ],*/
          ponderance: [
            { required: true, message: "请选择缓急程度", trigger: "blur" }
          ],
          securityClass: [
            { required: true, message: "请选择密级等级", trigger: "blur" }
          ],
        },
        // 判断是否为提交,还是添加
        open3: false,
        // 判断是否为提交,还是添加
        open4: false,
        // 部门
        deptOpen: false,
        // 部门树选项
        deptOptions: [],
        defaultProps: {
          children: "children",
          label: "label"
        },
        // 部门id
        depid: [],
        depname: [],
        deptflgOptions: [{
          "label": "单位",
          "value": 1
        }],
        loading: true,
        // 上传参数
        upload: {
          // 是否禁用上传
          isUploading: false,
          // 设置上传的请求头部
          headers: {Authorization: "Bearer " + getToken()},
          // 上传的地址
          url: process.env.VUE_APP_BASE_API + "/common/upload",
          // 上传的文件列表
          fileList: [],
          oldFileList:[]
        },

      };
    },
    created() {
      //flg 为流程状态,undefined:创建新的流程 1:打开代办中的流程, eles为查看流程详情
      this.flg = this.data.flg;
      //为 启动流程时的key值
      this.form.actkey = this.data.getactkey;
      //加载部门树表
      this.getTreeselect();
      if (this.flg == undefined) {
        this.open3 = true;
      } else if (this.flg == '1') {
        this.form = this.data;
        this.getDetails();
        this.open4 = true;
      } else {
        this.form = this.data;
        this.getDetails();
      }
    },
    methods: {

      /** 写 选择人员 按钮弹窗操作 */
      handleSelect() {
        this.$refs.selectUserByDept.childOpen = true
        this.Renopen = true
      },
      /** 写 选择人员 按钮弹窗操作 */
      handleSelectDept() {
        this.deptOpen = true;
        this.title = "发文部门";
      },
      //重新关闭office
      closeoffice(){
        this.$refs.ioffice.closeOffice();
      },
      selectOK(zh, xm) {
        this.form.sendUser = zh
        this.form.sendUserRealName = xm
        this.Renopen = false
      },
      /** --------------查询部门下拉树结构---------------- */
      getTreeselect() {
        treeselect().then(response => {
          this.deptOptions = response.data;
          var a = this.deptOptions;
          for (let i = 0; i < a.length; i++) {
            console.log(this.deptOptions[i].children[0].id)
            console.log(a[i].id)
          }

        });
      },
      // 所有部门节点数据
      getDeptAllCheckedKeys() {
        // 目前被选中的部门节点
        let checkedKeys = this.$refs.dept.getHalfCheckedKeys();
        // 半选中的部门节点
        let halfCheckedKeys = this.$refs.dept.getCheckedKeys();
        let a = this.$refs.dept.getCheckedNodes();
        var q = this.deptOptions;
        let e = "";
        for (let w = 0; w < q.length; w++) {
          e += q[w].children[w].id
        }
        for (let i = 0; i < a.length; i++) {
          if (a[i].id != 100 && a[i].id != e) {
            this.depname.push(a[i].label)
            this.depid.push(a[i].id)
          }
        }
        console.log(a)
        checkedKeys.unshift.apply(checkedKeys, halfCheckedKeys);
        // this.form.fwdept =this.depid;

        if (this.title == "主送部门") {
          this.form.avtiveSend = this.depname.toString();
        } else if (this.title == "抄送部门"){
          this.form.copyTo = this.depname.toString();;
        }else {
          this.form.fwdept = this.depname.toString();
        }
        this.deptOpen = false;
        this.depname = [];
        this.depid = [];
        return halfCheckedKeys;

      },

      //返回正文
      getcontent(data) {
        this.contentOpen = false;
        this.form.content = data;
        this.fileData.filePath = data;
      },

      // 文件提交处理
      submitUpload(item) {
        let uploadData = new FormData()
        uploadData.append('file',item.file)
        uploadFujian(uploadData).then(response => {
          if (response.code === 200) {
            this.upload.fileList.push(response.fileName);
            this.form.accessory=this.upload.fileList.toString()
            this.upload.oldFileList.push({
              name: response.fileName.substring(response.fileName.lastIndexOf("/")+1,response.fileName.length),
              url: response.url
            });
            this.msgSuccess("上传成功");
            this.upload.isUploading = false;
          }
        });
      },
      // 文件上传中处理
      handleFileUploadProgress(event, file, fileList) {
        this.upload.isUploading = true;
      },

      handlePreview(file) {
        // 预览,一些文件因为格式问题无法预览。推荐使用a标签，src为文件的下载地址，点击即可下载,参照录音
        window.open(file.url);
      },
      beforeRemove(file, fileList) {
        return this.$confirm(`确定移除 ${ file.name }？`);
      },
      handleRemove(file) {
        // 移除
        this.upload.oldFileList.forEach((item, index) => {
          if (item.uid === file.uid) {
            this.mail.oldFileList.splice(index, 1);
            //删除
          }
        });
      },

      //获取详细信息，修改用到
      getDetails() {
        getFormData(this.form.formId).then(response => {
          this.form = response.data;
          this.fileData.filePath = this.form.content==""?"/profile/doc/NewCreate.doc":this.form.content;
          this.fileData.user = this.form.user;
          if (response.data.accessory!=""){
            var files= response.data.accessory.split(",")
            for (var i=0;i<files.length;i++){
              var fiellist={
                "name":files[i].substring(files[i].lastIndexOf("/")+1,files[i].length),
                "url":process.env.VUE_APP_BASE_API+files[i]
              }
              this.upload.oldFileList.push(fiellist)
            }
          }

        });
      },
      openda() {
        this.open1 = false;
      },

      //打开weboffice 页面添加正文
      openIweboffice() {
        // this.$router.push({path:'/actwork/fw/iweboffice'})
        this.timer = new Date().getTime()
        this.contentOpen = true;
      },

      // 取消按钮
      cancel() {
        this.$emit('getList');
        this.open = false;
        this.reset();

      },
      cancel1(){
        this.contentOpen = false;
      },
      // 表单重置
      reset() {
        this.form = {
          everyone: undefined,
        };
        this.resetForm("form");
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.pageNum = 1;
        // this.getList();
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.resetForm("queryForm");
        this.handleQuery();
      },
      // 多选框选中数据
      handleSelectionChange(selection) {
        this.ids = selection.map(item => item.id)
        this.single = selection.length != 1
        this.multiple = !selection.length
      },
      /** 新增按钮操作 */
      handleAdd() {
        this.reset();
        this.open = true;
        this.title = "公文发文";
      },
      //关闭部门窗口
      cancelDept(){
        this.deptOpen=false;
      },

      /** 修改按钮操作 */
      handleUpdate(row) {
        this.reset();
        const id = row.id || this.ids
        getInfo(id).then(response => {
          this.form = response.data;
          this.open = true;
          this.title = "公文发文";
        });
      },
      handleUpdate1(row) {
        this.reset();
        const id = row.id || this.ids
        getInfo(id).then(response => {
          this.form = response.data;
          this.open1 = true;
          this.title = "公文发文";
        });
      },
      /** 提交按钮 */
      submitForm: function (flg) {
        this.$refs["form"].validate(valid => {
          this.$set(this.form, "sendFlg", flg)
          if (valid) {
            if (this.form.id != undefined) {
              updateInfo(this.form).then(response => {
                if (response.code === 200) {
                  this.msgSuccess("修改成功");
                  // this.getList();
                }
              });
            } else {
              submitYljApply(this.form).then(response => {
                console.log(response.code)
                if (response.code === 200) {
                  console.log(response.code)
                  this.msgSuccess("提交成功");
                  // this.open = false;
                  this.$emit('transferUser', this.open)
                }
              });
            }
          }
        });
      },
      submitToDo() {
        updateInfo(this.form).then(response => {
          submitToDoItem(this.form.taskid).then(response1 => {
            this.msgSuccess("提交成功");
            console.log(response1.code)
            this.$emit('getList');
          });
        })
      },
      //拒绝按钮
      deleteToDo() {
        this.$confirm('是否确认拒绝这这个申请吗?', '警告', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          deleteToDoItem(this.form.taskid).then(response => {
            this.msgSuccess("拒绝成功")
            this.$emit('getList');
          })

        }).catch(() => {
        });

      },
      /** 删除按钮操作 */
      handleDelete(row) {
        const ids = row.id || this.ids;
        this.$confirm('是否确认删除这一封邮件?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function () {
          return delInfo(ids);
        }).then(() => {
          // this.getList();
          this.msgSuccess("删除成功");
        }).catch(function () {
        });
      },
      /** 导出按钮操作 */
      handleExport() {
        const queryParams = this.queryParams;
        this.$confirm('是否确认导出所有【请填写功能名称】数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function () {
          return exportInfo(queryParams);
        }).then(response => {
          this.download(response.msg);
        }).catch(function () {
        });
      }
    },
  };
</script>

<style lang="less" scoped>
  .apple {
    width: 150px;
    overflow: hidden;
    white-space: nowrap;
    text-overflow: ellipsis;
  }

  .title {
    font-size: 30px;
    text-align: center;
    margin-top: 30px;
  }

  .bottom10 {
    margin-bottom: 20px;
  }

  .el-dialog__title {
    text-align: center;
    font-weight: bold;
  }

  table {
    border-collapse: collapse;
  }

  .el-form-item {
    margin-bottom: 10px !important;
    margin-top: 10px;
  }

  .dialog-footer {
    text-align: center;
    margin-top: 20px;
  }
</style>
