<template>
  <div class="wrapper editwrap">
    <el-dialog
      :visible.sync="reVisible"
      :title="stype == 'a' ? '事件评估' : '事件处置'"
      :show-close="false"
      :close-on-click-modal="false"
    >
      <!-- 事件评估 -->
      <el-form
        ref="editFormA"
        :model="editFormA"
        :rules="rulesA"
        label-width="100px"
        v-show="stype == 'a'"
      >
        <el-form-item label="评估内容" prop="evaluateContent">
          <div id="editorA"></div>
        </el-form-item>
        <el-form-item label="材料文件" v-if="editFormA.id == null || editFormA.id == ''">
          <el-upload
                  ref="uploaderA"
                  class="uploader"
                  :limit="1"
                  :action="actionUrl"
                  :on-success="(a,b,c) => onSuccessA(a,b,c,'fileUrl')"
                  :on-error="onErrorA"
                  :on-remove="handleRemoveA"
                  :before-remove="(a,b,c) => beforeRemoveA(a,b,c,'fileUrl')"
                  :on-exceed="onExceedA"
                  :before-upload="beforeUploadA"
                  :multiple="false"
                  list-type="picture"
                  :file-list="fileListA"
          >
            <i class="el-icon-plus"></i>
            <div slot="tip" class="el-upload__tip" >只能上传doc/docx/pdf/xls/xlsx格式文件，且不超过一个</div>
          </el-upload>
        </el-form-item>
        <el-form-item label="材料文件" v-if="editFormA.id != null && editFormA.id != '' &&
                                          editFormA.fileUrl != '' && editFormA.fileUrl != null">
          <span
                class="dbtn sd qiCr"
                @click="checkFile(editFormA.fileUrl)"
          >
            <i class="el-icon el-icon-view"></i>
            {{editFormA.fileOriginalName}}
          </span>
        </el-form-item>
        <el-form-item label="备注" prop="remarks">
          <el-input type="textarea" v-model="editFormA.remarks"></el-input>
        </el-form-item>
      </el-form>
      <!-- 事件处置 -->
      <el-form
        ref="editFormB"
        :model="editFormB"
        :rules="rulesB"
        label-width="100px"
        v-if="stype == 'b'"
      >
        <div v-if="stepArr.length > 0">
          <el-steps :space="150" finish-status="success">
            <el-step
              v-for="(it, index) in stepArr"
              :key="index"              
              :description="it.handleTime"
              @click.native="stepClick(it)"
              :class="{'active': it.id == currenstepId}"
            >
				<el-tooltip slot="title" :content="it.handleContent" class="item" effect="dark" placement="bottom" >
				     <!-- <div slot="content" :content="it.handleContent" style="width: 150px;word-wrap: break-word;word-break: break-all;overflow: hidden;"></div> -->
					<p style="width: 150px; overflow: hidden;text-overflow: ellipsis;white-space: nowrap;">{{it.handleContent}}</p>
				</el-tooltip>
			</el-step>
          </el-steps>
        </div>
        <el-form-item label="处理内容" prop="handleContent">
          <el-input type="textarea" v-model="editFormB.handleContent"></el-input>
        </el-form-item>
        <el-form-item label="处理时间" prop="handleTime">
          <el-date-picker
            v-model="editFormB.handleTime"
            type="datetime"
            placeholder="选择日期时间"
            align="right"
            value-format="yyyy-MM-dd HH:mm:ss"
          ></el-date-picker>
        </el-form-item>
        <el-form-item label="材料文件">
          <el-upload
                  ref="uploaderB"
                  class="uploader"
                  :limit="1"
                  :action="actionUrl"
                  :on-success="(a,b,c) => onSuccessB(a,b,c,'fileUrl')"
                  :on-error="onErrorB"
                  :on-remove="handleRemoveB"
                  :before-remove="(a,b,c) => beforeRemoveB(a,b,c,'fileUrl')"
                  :on-exceed="onExceedB"
                  :before-upload="beforeUploadB"
                  :multiple="false"
                  list-type="picture"
                  :file-list="fileListB"
                  v-if=""
          >
            <i class="el-icon-plus"></i>
            <div slot="tip" class="el-upload__tip" >只能上传doc/docx/pdf/xls/xlsx格式文件，且不超过一个</div>
          </el-upload>
          <span
                  class="dbtn sd qiCr"
                  @click="checkFile(editFormB.fileUrl)"
                  v-if="editFormB.fileUrl != '' && editFormB.fileUrl != null"
          >
            <i class="el-icon el-icon-view"></i>
            点击下载
          </span>
        </el-form-item>
        <el-form-item label="备注" prop="remarks">
          <el-input type="textarea" v-model="editFormB.remarks"></el-input>
        </el-form-item>
        <el-form-item>
            <el-button @click="addStep()" v-if="currenstepId == '' && eventStatus != '4'">
              <i class="el-icon-sort-up"></i>提交处理过程
            </el-button>
            <el-button @click="addStep()" v-if="currenstepId != '' && eventStatus != '4'">
              <i class="el-icon-sort-up"></i>提交修改
            </el-button>
            <el-button @click="delStep()" v-if="currenstepId != '' && eventStatus != '4'">
              <i class="el-icon-delete"></i>删除当前
            </el-button>
            <el-button @click="currenstepId = '';editFormB = {};fileListB = []" v-if="currenstepId != '' && eventStatus != '4'">
              <i class="el-icon-plus"></i>增加过程
            </el-button>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" size="small" @click="confirmFun()" v-if="stype == 'a' && eventStatus != '4'">确定</el-button>
        <el-button @click="$emit('redialogFun')" size="small">取消</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<style lang="scss">
@import '@/utils/default.scss';
</style>
<script lang="ts">
import { Component, Vue, Provide, Prop, Watch } from "vue-property-decorator";
import { State, Getter, Mutation, Action } from "vuex-class";
import METHOD from "@/utils/methods";
let uploadfile = require("@/assets/uploadfile.png");
@Component({
  components: {}
})
export default class ProcessEventsEdit extends Vue {
  @Prop(String) eventId!: String;
  @Prop(Boolean) reVisible!: Boolean;
  @Prop(String) stype!: string;
  @Prop(String) eventStatus!: string;
  //上传
  @Provide() actionUrl: any = "";
  @Provide() fileUrl: any = [];
  @Provide() fileListA: any = [];
  @Provide() fileListB: any = [];

  @Provide() rulesA: any = {
    // evaluateContent: [
    //   { required: true, trigger: "change", message: "该项为必填项！" }
    // ],
  };
  @Provide() rulesB: any = {
    handleTime: [
      { required: true, trigger: "blur", message: "该项为必填项！" }
    ],
    handleContent: [
      { required: true, trigger: "blur", message: "该项为必填项！" }
    ]
  };
  @Provide() editorA: any;
  @Provide() editFormA: any = {};
  @Provide() editFormB: any = {};
  @Provide() stepArr: any = [];
  @Provide() currenstepId: string = '';//当前选中step
  @Watch("fileUrl") change(val: any) {
    if(this.stype == 'a'){
      if (val.length > 0) {
        this.editFormA.fileUrl = val[0].response.data.viewPath;
        this.editFormA.fileOriginalName = val[0].response.data.originalName;

        this.fileListA = [];
        this.fileListA.push({
          name: this.editFormA.fileOriginalName,
          url: uploadfile,
        });
      } else {
        this.editFormA.fileUrl = "";
        this.editFormA.fileOriginalName = "";
      }
      console.log("this.fileListA", this.fileListA)
    } else {
      if (val.length > 0) {
        this.editFormB.fileUrl = val[0].response.data.viewPath;
        this.editFormB.fileOriginalName = val[0].response.data.originalName;

        this.fileListB = [];
        this.fileListB.push({
          name: this.editFormB.fileOriginalName,
          url: uploadfile,
        });
      } else {
        this.editFormB.fileUrl = "";
        this.editFormB.fileOriginalName = "";
      }
      console.log("this.fileListB", this.fileListB)
    }

  }
  //创建编辑器
  creatEditor() {
    this.editorA = new ice.editor("editorA");
    //自定义编辑器工具栏菜单（默认展示所有功能）
    this.editorA.menu = [
      "fontSize",
      "foreColor",
      "bold",
      "italic",
      "underline",
      "strikeThrough",
      "line",
      "justifyLeft",
      "justifyCenter",
      "justifyRight",
      "line",
      "table",
      "insertImage",
      "insertOrderedList",
      "insertUnorderedList",
      "indent"
    ];
    this.editorA.height = "200px";
    this.editorA.create();
  }
  getPGdata(){
    let that = this;
    (that as any).$axios.get(`/eventInfo/getEventEvaluateInfoByEventId/${that.eventId}`).then(
      (res:any) => {
        if(res){
          that.editFormA = Object.assign({}, res);
          that.editorA.setValue(res.evaluateContent)
        }
      }
    )
  }
  getCLdata(){
    let that = this;
    (that as any).$axios.get(`/eventInfo/getEventHandleProcessListByEventId/${that.eventId}`).then(
      (res:any) => {
        if(res){
          that.stepArr =  res
        }
      }
    )
  }
  //取消事件要在父级取消是所以用到 $emit
  confirmFun() {
    let that = this;
    (that as any).$refs['editFormA'].validate((valid: boolean) => {
      if( that.editorA.getText() == false ) {
        (that as any).$message.error('请输入评估内容！');
        return
      }
      that.editFormA.evaluateContent =  that.editorA.getHTML()
      if (valid) {
        that.postPGData();
      } else {
        return false;
      }
    });
  }
  delStep(){
    let that = this;
    METHOD.deleteFun(that, `/eventInfo/deleteEventHandleProcessInfoById/${that.currenstepId}`, function() {
      that.getCLdata();
    });
  }
  addStep() {
    let that = this;
    (that as any).$refs['editFormB'].validate((valid: boolean) => {
      if (valid) {
        // that.stepArr.push(Object.assign({}, that.editFormB));
        that.postCLData()
      } else {
        return false;
      }
    });
  }
  stepClick(item: any){
    console.log(item)
    let that = this;
    that.currenstepId = item.id;
    that.editFormB = Object.assign({}, item)
    console.log("that.editFormB",that.editFormB)
    if (that.editFormB.fileOriginalName) {
      this.fileListB = [];
      this.fileListB.push({
        name: that.editFormB.fileOriginalName,
        url: uploadfile,
      });
    } else {
      this.fileListB = [];
    }
  }
  postPGData() {
    let that = this;
    console.log("that.editFormA", that.editFormA);
    (that as any).$axios
      .post(
        `/eventInfo/addOrEditEventEvaluateInfo`,
        Object.assign({eventId: that.eventId},that.editFormA)
      )
      .then((res: any) => {
        (that as any).$message.success('成功！');
        that.$emit('redialogFun');
        that.$emit("refreshTableData"); //刷新表格
      });
  }
  //对数组去重排序
  sortOut(arr: Array<any>){
    const compare = (a:any, b:any) => {
      if(a.handleTime > b.handleTime) return -1;
      else if(a.handleTime = b.handleTime) return 0;
      else return 1;
    }
    arr.sort(compare)
  }
  postCLData() {
    let that = this;
    (that as any).$axios
      .post(
        `/eventInfo/addOrEditEventHandleProcessInfo`,
        Object.assign({ eventId: that.eventId }, that.editFormB)
      )
      .then((res: any) => {
        (that as any).$message.success('成功！');
          that.getCLdata()
      });
  }
  // 上传
  onSuccessA(res: any, file: any, fileListA: any, key: string) {
    this.$data[key] = fileListA;
  }
  onErrorA(err: any, file: any, fileListA: any) {
    this.$message.error("上传失败!");
  }
  handleRemoveA(file: any, fileListA: any, key: string) {
    this.$data[key] = fileListA;
    this.editFormA.fileUrl = "";
    this.editFormA.fileOriginalName = "";
  }
  onExceedA(file: any, fileListA: any) {
    this.$message.warning("只允许上传一个文件，如需更改请先删除！");
  }
  beforeRemoveA(file: any, fileListA: any) {
    if (file && file.status==="success") {
      let that = this,
              param;
      param = file.response
              ? file.response.data.savePath.replace(/\\/g, "%")
              : file.url.replace(/\\/g, "%").slice(9);
      METHOD.axiosGet(this, `/file/deleteFile?savePath=${param}`, function (
              res: any
      ) {
        if (res.code == 0) that.$message.success("删除成功");
        else return false;
      });
    }
  }
  beforeUploadA(file: any){
    console.log(file)
    var testmsg=file.name.substring(file.name.lastIndexOf('.')+1)
    const extension = testmsg === 'xls'
    const extension2 = testmsg === 'xlsx'
    const extension3 = testmsg === 'doc'
    const extension4 = testmsg === 'docx'
    const extension5 = testmsg === 'pdf'
    if(!extension && !extension2 && !extension3 && !extension4 && !extension5) {
      this.$message({
        message: '上传文件只能是doc、docx、pdf、xls、xlsx格式!',
        type: 'warning'
      });
    }
    return extension || extension2 || extension3 || extension4 || extension5
  }
  // 上传
  onSuccessB(res: any, file: any, fileListB: any, key: string) {
    this.$data[key] = fileListB;
  }
  onErrorB(err: any, file: any, fileListB: any) {
    this.$message.error("上传失败!");
  }
  handleRemoveB(file: any, fileListB: any, key: string) {
    this.$data[key] = fileListB;
    this.editFormB.fileUrl = "";
    this.editFormB.fileOriginalName = "";
  }
  onExceedB(file: any, fileListB: any) {
    this.$message.warning("只允许上传一个文件，如需更改请先删除！");
  }
  beforeRemoveB(file: any, fileListB: any) {
    if (file && file.status==="success") {
      let that = this,
              param;
      param = file.response
              ? file.response.data.savePath.replace(/\\/g, "%")
              : file.url.replace(/\\/g, "%").slice(9);
      METHOD.axiosGet(this, `/file/deleteFile?savePath=${param}`, function (
              res: any
      ) {
        if (res.code == 0) that.$message.success("删除成功");
        else return false;
      });
    }
  }
  beforeUploadB(file: any){
    console.log(file)
    var testmsg=file.name.substring(file.name.lastIndexOf('.')+1)
    const extension = testmsg === 'xls'
    const extension2 = testmsg === 'xlsx'
    const extension3 = testmsg === 'doc'
    const extension4 = testmsg === 'docx'
    const extension5 = testmsg === 'pdf'
    if(!extension && !extension2 && !extension3 && !extension4 && !extension5) {
      this.$message({
        message: '上传文件只能是doc、docx、pdf、xls、xlsx格式!',
        type: 'warning'
      });
    }
    return extension || extension2 || extension3 || extension4 || extension5
  }
  checkFile(url: any) {
    window.open("http://" + METHOD.GlobalUrl + "/ioc" + url)
  }
  created() {
    let that = this;
    if( that.stype == 'a'){
      that.$nextTick(() => {
        that.creatEditor();
      });
      that.getPGdata();
    } else {
      that.getCLdata()
    }
    if (that.editFormB.fileOriginalName) {
      that.fileListB.push({
        name: that.editFormB.fileOriginalName,
        url: uploadfile,
      });
    }
    that.actionUrl = "http://" + METHOD.GlobalUrl + "/ioc/file/uploadFile";
  }
}
</script>