<!-- 站内消息/新增/修改 -->
<template>
  <div class="addModifyPage">
    <div style="width: 800px; margin: 0 auto; margin-bottom: 20px;">
      <el-row>
        <el-col :span="20">
          <el-form
            :model="inventoryCheckMonthVO"
            :rules="rules"
            ref="inventoryCheckMonthVO"
            label-width="120px"
            class="demo-ruleForm"
          >
            <el-form-item label="消息标题" prop="title">
              <el-input
                placeholder="请输入标题"
                v-model="inventoryCheckMonthVO.title"
                autocomplete="off"
                :disabled="isDisabled"
              ></el-input>
            </el-form-item>
            <el-form-item label="发件人" prop="sender" v-show="isDisabled">
              <el-input
                v-model="inventoryCheckMonthVO.sender"
                autocomplete="off"
                :disabled="isDisabled"
              ></el-input>
            </el-form-item>
            <el-form-item label="收件人" prop="receiver" v-show="isshow">
              <div style="display: flex;">
                <el-input
                  v-model="inventoryCheckMonthVO.receiver"
                  autocomplete="off"
                  :disabled="true"
                ></el-input>
                <el-button @click="openChangeModal" icon="el-icon-search"></el-button>
              </div>
            </el-form-item>
            <el-form-item label="附件" class="attachmentStyle">
              <el-upload
                class="upload-demo"
                ref="upload"
                :action="fileUrl"
                :on-success="handleSuccess"
                :on-error="handleerror"
                :on-preview="handlePreview"
                :on-remove="handleRemove"
                :before-upload="handleBeforeUpload"
                :file-list="fileList"
                :limit="3"
                :auto-upload="true"
              >
                <el-button :disabled="isDisabled" slot="trigger" type="primary" class="outCancelButton">选取文件</el-button>
                <!-- <el-button style="margin: 0 50px; width: 80px;" type="primary" class="button newReport" v-show="isshow">查看附件</el-button> -->
                <!-- <el-popover placement="right" width="400" trigger="click"> -->
                  <el-table :data="tableFileList" border stripe highlight-current-row>
                    <el-table-column property="name" label="文件名" :show-overflow-tooltip='true' align="center"></el-table-column>
                    <el-table-column property label="操作" align="center">
                      <template slot-scope="scope">
                        <el-tooltip class="item" effect="light" content="下载" placement="top">
                          <el-button
                            type="primary"
                            @click="downloadClick(scope.row)"
                            size="mini"
                            icon="el-icon-download"
                            class="button"
                          ></el-button>
                        </el-tooltip>
                        <el-tooltip class="item" effect="light" content="删除" placement="top">
                          <el-button
                            v-show="isshow"
                            type="primary"
                            @click="deleteFileBtn(scope.row)"
                            size="mini"
                            icon="el-icon-delete"
                            class="difStateDelBtn"
                          ></el-button>
                        </el-tooltip>
                      </template>
                    </el-table-column>
                  </el-table>
                  <el-button
                    v-if="downloadIsShow"
                    slot="reference"
                    type="primary"
                    class="outCancelButton"
                  >查看附件</el-button>
                <!-- </el-popover> -->
                <div slot="tip" class="el-upload__tip"></div>
              </el-upload>
            </el-form-item>
            <el-form-item label="通知内容" class="textClass" prop="contens">
              <el-input
                type="textarea"
                class="minH"
                :rows="2"
                placeholder="请输入内容"
                :disabled="isDisabled"
                resize="none"
                v-model="inventoryCheckMonthVO.contens"
              ></el-input>
            </el-form-item>
          </el-form>
        </el-col>
      </el-row>
      <ChoosePerson
        :changeModalShow="changeModalShow"
        :personItem="personItem"
        :dataTree="dataTree"
        :queryedData="queryedData"
        v-on:closeModal="closeChangeModal"
        v-on:submitDataClick="submitData"
        v-on:personItem="searchClick"
      ></ChoosePerson>
      <el-row class="btnSetinve">
        <div style="width: 80%; margin: 0 auto; text-align: center; ">
          <el-button
            style="margin: 0 50px;"
            type="primary"
            class="outCancelButton"
            @click="goBack"
          >返回</el-button>
          <el-button
            :loading="loading"
            style="margin: 0 50px;"
            type="primary"
            class="outCancelButton"
            v-show="isshow"
            @click="sendClick(0, 'inventoryCheckMonthVO')"
          >存为草稿</el-button>
          <el-button
            :loading="loading"
            style="margin: 0 50px;"
            type="primary"
            class="outCancelButton"
            v-show="isshow"
            @click="sendClick(1, 'inventoryCheckMonthVO')"
          >发送</el-button>
        </div>
      </el-row>
    </div>
  </div>
</template>
<script>
import {
  findByIdZnx,
  sendSave,
  findByIdsend,
  updateLetter,
  deleteFile,
  getTreeData,
  getInfoById,
  getDataTreeCode,
  getUsers
} from "@/api/znx/index";
import { file, fileDownload } from "@/api/index";
import ChoosePerson from "@/components/ChoosePerson/index";
export default {
  data() {
    return {
      rules: {
        title: [{ required: true, message: "请输入标题", trigger: "blur" }],
        receiver: [
          { required: true, message: "请输入发件人", trigger: "blur" }
        ],
        contens: [
          { required: true, message: "请输入信息内容", trigger: "blur" }
        ]
      },
      inventoryCheckMonthVO: {
        title: "",
        sender: "",
        contens: "",
        receiver: "",
        receiverIds: "",
        receiverType: "2",
        sendStatus: "",
        attachIds: [],
        id: ""
      },
      userId: "",
      releaseName: "",
      GetUserId: null,
      isDisabled: "",
      isshow: "",
      fileUrl: `${file}`,
      arrList: [],
      fileList: [],
      tableFileList: [],
      downloadIsShow: "",
      loading: false,
      changeModalShow: false,
      personItem: [],
      dataTree: [], // 审核单位树形数据
      allInfo: null,
      queryedData: []
      // token: null
    };
  },
  props: ['flag','rowId'],
  components: {
    ChoosePerson
  },
  methods: {
    searchClick(data) {
     
      getUsers(data).then(res=>{
        this.personItem = res.data;
        // console.log(this.personItem)
      })
      // console.log(data,123);
    },
    openChangeModal() {
      /*打开对话框事件*/
      let needData = {
        deptName: "",
        name: "",
        orgName: "",
        userAccount: ""
      };
      getTreeData(needData).then(res => {
        // console.log(res);
        if (res.infoCode == 200) {
          this.personItem = res.data;
          this.changeModalShow = true;
          this.allQueryData();
        }
      });
   
    },
    allQueryData() {
      //所有的数据
      const needQueryData = this.personItem;
      let needArr = [];
      for (let i = 0; i < needQueryData.length; i++) {
        if (needQueryData[i].userName) {
          needArr.push(needQueryData[i].userName);
        }
        if (needQueryData[i].userAccount) {
          //账号
          needArr.push(needQueryData[i].userAccount);
        }
        if (needQueryData[i].deptName) {
          //单位名称
          needArr.push(needQueryData[i].deptName);
        }
        if (needQueryData[i].orgName) {
          //组织名
          needArr.push(needQueryData[i].orgName);
        }
      }
      this.queryedData = needArr.join("");
      // console.log("所有的所有的所有的", this.queryedData);
    },
    closeChangeModal(data) {
      /*对话框关闭事件*/
      data ? (this.changeModalShow = false) : null;
    },
    submitData(data) {
      /*对话框确定事件*/
      // console.log("pppppppppppppppp", data);
      data ? (this.changeModalShow = false) : null;
      let arr = data.map(item => {
        return item.userName;
      });
      let arr1 = data.map(item => {
        return item.id;
      });
      // this.inventoryCheckMonthVO.receiverIds=JSON.stringify(arr1)
      // this.inventoryCheckMonthVO.receiver=arr
      //人员名称
      this.inventoryCheckMonthVO.receiver = arr.join(",");
      //人员id
      this.inventoryCheckMonthVO.receiverIds = arr1.join(",");
      // console.log(
      //   "已选的数据",
      //   arr,
      //   arr1
      // ); /*data存放的是被选人员名单的id及name*/
    },
    // 判断是否是新增还是查看按钮进入该页面，表单是否只读
    isDisabledFun() {
      // flag为3是收件箱查看按钮进入 1为新增按钮进入 2位发件箱查看按钮进入 4为修改按钮进入
      if (this.flag == 3) {
        this.downloadIsShow = true;
        this.isDisabled = true;
        this.isshow = false;
        // console.log(this.downloadIsShow);
        this.getMsg();
      } else if (this.flag == 1) {
        this.downloadIsShow = false;
        this.isDisabled = false;
        this.isshow = true;
      } else if (this.flag == 2) {
        this.downloadIsShow = true;
        this.isDisabled = true;
        this.isshow = false;
        this.sendgetMsg();
      } else {
        this.downloadIsShow = true;
        this.isDisabled = false;
        this.isshow = true;
        this.sendgetMsg();
      }
    },
    // 收件箱 根据id 查询详情信息
    getMsg() {
      findByIdZnx(this.rowId).then(res => {
        this.inventoryCheckMonthVO = res.data;
        // console.log(res.data, "修改");
        if (res.data.attachIds.length > 0) {
          this.tableFileList = JSON.parse(res.data.attachIds);
          this.fileList = this.tableFileList;
        }
      });
    },
    // 发件箱 根据id 查询详情信息
    sendgetMsg() {
      findByIdsend(this.rowId).then(res => {
        this.inventoryCheckMonthVO = res.data;
        // console.log(res.data, "修改");
        if (res.data.attachIds.length > 0) {
          this.tableFileList = JSON.parse(res.data.attachIds);
          this.fileList = this.tableFileList;
        }
      });
    },
    // 发送或存为草稿箱click
    sendClick(num, formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          // console.log(this.inventoryCheckMonthVO);
          if (this.inventoryCheckMonthVO.receiver == "") {
            this.$message({
              type: "warning",
              message: `请选择收件人`
            });
          }
          this.inventoryCheckMonthVO.attachIds = JSON.stringify(this.tableFileList);
          this.inventoryCheckMonthVO.sendStatus = num;
          if (this.rowId == undefined) {
            sendSave(this.inventoryCheckMonthVO).then(res => {
              this.loading = true;
              if (res.infoCode == 200) {
                this.$parent.fGoBack();
                // this.$router.push({
                //   path: "/sso/znxsend"
                // });
              } else {
                this.$message({
                  type: "error",
                  message: res.msg
                });
                this.loading = false;
              }
            }).catch(err => {
              console.log(err)
              this.loading = false;
            })
          } else {
            this.inventoryCheckMonthVO.id = this.rowId;
            this.loading = true;
            this.inventoryCheckMonthVO.attachIds = JSON.stringify(this.tableFileList);
            // console.log(this.inventoryCheckMonthVO);
            updateLetter(this.inventoryCheckMonthVO).then(res => {
              if (res.infoCode == 200) {
                this.$parent.fGoBack();
                // this.$router.push({
                //   path: "/sso/znxsend"
                // });
              } else {
                this.$message({
                  type: "error",
                  message: res.msg
                });
                this.loading = false;
              }
            }).catch(err => {
              console.log(err)
              this.loading = false;
            })
          }
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    // 返回按钮
    goBack() {
      this.$parent.fGoBack();
      //this.$router.back(-1);
    },
    // 下载按钮
    downloadClick(row) {
      window.location = `${fileDownload}?id=${row.id}`;
    },
    // 附件删除按钮
    deleteFileBtn(row) {
      // console.log(this.tableFileList);
      deleteFile(row.id).then(res => {
        if (res.infoCode == 200) {
          if (this.tableFileList.length > 0) {
            for (const i in this.tableFileList) {
              if (row.id == this.tableFileList[i].id) {
                this.tableFileList.splice(i, 1);
              }
            }
          }
          // console.log(this.tableFileList, 123123);
          this.inventoryCheckMonthVO.attachIds = JSON.stringify(
            this.tableFileList
          );
        } else {
          this.$message({
            type: "error",
            message: res.msg
          });
        }
      });
    },
    handleRemove(file, fileList) {
      // console.log(file, fileList);
    },
    handlePreview(file) {
      // console.log(file);
    },
    handleSuccess(response, file, fileList) {
      this.$message({
        type: "success",
        message: response.msg
      });
      //this.arrList.push({ id: response.data.id, name: response.data.name });
      this.tableFileList.push({ id: response.data.id, name: response.data.name });
    },
    handleerror(err, file, fileList) {
      this.$message({
        type: "error",
        message: "上传失败"
      });
    },
    handleBeforeUpload(file) {
      // console.log(file);
    },
    openChangeModal() {
      /*打开对话框事件*/
      getTreeData({ token: this.token }).then(res => {
        if (res.infoCode == 200) {
          this.personItem = res.data;
          // console.log( this.personItem ,123123)
          this.changeModalShow = true;
        }
      });
      getDataTreeCode("AREA_CODE").then(res => {
        // console.log("字典服务", res);
        this.dataTree=res.data
      });
    },
    closeChangeModal(data) {
      /*对话框关闭事件*/
      data ? (this.changeModalShow = false) : null;
    }
    // submitData(data){   /*对话框确定事件*/
    //     data ? this.changeModalShow = false : null;
    //     let arr = [];
    //     let arrId = [];
    //     data.map(function(item,index) {
    //       arr.push(item.name);
    //       arrId.push(item.id);
    //     })
    //     //人员名称
    //     this.inventoryCheckMonthVO.receiver = arr.join(",");
    //     //人员id
    //     this.inventoryCheckMonthVO.receiverIds = arrId.join(",");
        // console.log(this.inventoryCheckMonthVO)
        // console.log('已选的数据',data)  /*data存放的是被选人员名单的id及name*/
    // },
  },
  created() {
    // this.GetUserId = localStorage.getItem("idOa");
    // this.getUserInfo()
    this.isDisabledFun();
    // window.localStorage.getItem("token") ? this.token = window.localStorage.getItem("token") : null
  },
  mounted() {}
};
</script>
<style>
  .addModifyPage .el-form-item.attachmentStyle {
      margin-bottom: 5px;
  }
  .addModifyPage .textClass .el-form-item__label {
    line-height: 20px;
  }
  .addModifyPage .minH .el-textarea__inner {
    min-height: 100px !important;
  }
  .addModifyPage  .el-upload-list{ display: none;}
</style>


