<template>
  <div class="wrapper editwrap w100">
    <el-dialog
      :visible.sync="dialogVisible"
      :title="title"
      :show-close="false"
      :close-on-click-modal="false"
    >
      <el-row :gutter="20">
        <el-col :span="12" class="flcolum">
          <div>
            <div class="yatit">预案基本信息</div>
            <el-form ref="editForm" :model="editForm" :rules="rules" label-width="100px">
              <el-form-item label="所属部门" prop="deptId">
                <el-select v-model="editForm.deptId" placeholder="请选择" @change="seletChange">
                  <el-option
                    v-for="item in deptsArr"
                    :key="item.id"
                    :label="item.fullName"
                    :value="item.id.toString()"
                  ></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="预案标题" prop="planTitle">
                <el-input v-model="editForm.planTitle"></el-input>
              </el-form-item>
              <el-form-item label="预案分类" prop="planType">
                <!--<el-input v-model="editForm.planType"></el-input>-->
                <el-select v-model="editForm.planType" placeholder="请选择" @change="seletChangeplanEventSortArr">
                  <el-option
                          v-for="item in planEventSortArr"
                          :key="item.dictId"
                          :label="item.name"
                          :value="item.dictId.toString()"
                  ></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="预案等级" prop="planLevel">
                <el-radio-group v-model="editForm.planLevel">
                  <el-radio label="Ⅰ">Ⅰ级</el-radio>
                  <el-radio label="Ⅱ">Ⅱ级</el-radio>
                  <el-radio label="Ⅲ">Ⅲ级</el-radio>
                </el-radio-group>
              </el-form-item>
              <el-form-item label="预案内容" prop="planContents">
                <textarea id="editorA" v-model="editForm.planContents"></textarea>
              </el-form-item>
             <!-- <el-form-item label="短信模板" prop="smsModel">
                <el-input
                        v-model="editForm.smsModel"
                        type="textarea"
                        maxlength="256"
                        show-word-limit
                />
              </el-form-item>-->
              <el-form-item label="备注" prop="remarks">
                <el-input type="textarea" v-model="editForm.remarks"></el-input>
              </el-form-item>
            </el-form>
          </div>
        </el-col>
        <el-col :span="12" class="flcolum">
          <div>
            <div class="yatit">预案关联部门</div>
            <el-transfer
              v-model="rdeptArr"
              :data="NumberArr"
              :props="NumbersProps"
              :titles="['人员列表','已选择']"
              :render-content="renderFunc"
              :format="{
                noChecked: '${total}',
                hasChecked: '${checked}/${total}'
              }"
              :right-default-checked="['1176851970218463234']"
              @change="handleChange"></el-transfer>
            <span style="margin-top: 20px;display: block;">短信模板：</span>
            <div style="margin-top: 15px;" v-for="item in smsDepartments">
              <span style="float: left;width: 22%;text-align: right">{{item.deptName}}：</span>
              <el-input
                      type="textarea"
                      maxlength="256"
                      show-word-limit
                      style="width: 78%"
                      v-model="item.smsModel"
              />
            </div>

            <!--<div style="border: solid 1px ">

            </div>-->
          </div>
        </el-col>
      </el-row>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" size="small" @click="confirmFun('editForm')">提交预案</el-button>
        <el-button @click="$emit('dialogFun')" size="small">取消编辑</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<style lang="scss">
.w100 .el-dialog {
  width: 80%;
  .flcolum {
    > div {
      border-radius: 3px;
    }
  }
  .el-col-12{width:49%}
  .yatit {
    background: #4273bd;
    color: #ffffff;
    line-height: 2;
    height: 2em;
    text-align: center;
    margin-bottom: 10px;
    border-radius: 2px;
  }
  .el-transfer-panel {
    width: calc((100% - 116px) / 2);
  }
  .el-transfer__buttons {
    width: 56px;
  }
  .el-transfer__button {
    margin-left: 0;
    display: block;
  }
}
</style>
<script lang="ts">
import { Component, Vue, Provide, Prop, Watch } from "vue-property-decorator";
import { State, Getter, Mutation, Action } from "vuex-class";
import City from "@/components/city.vue";
import METHOD from "@/utils/methods";
@Component({
  components: { City }
})
export default class PlansMgEdit extends Vue {
  // @Getter('signs') signsData: any;
  //属性或参数中使用!:表示强制解析（告诉typescript编译器，这里一定有值），常用于vue-decorator中的@Prop
  @Prop(Boolean) dialogVisible!: Boolean;
  @Prop(String) title!: String;
  @Prop(String) id!: String;

  @Provide() editForm: any = {
    id: "",
    planContents: "",
    rdeptInfoList: [],
    deptName: ""
  };

  @Provide() rules: any = {
    deptId: [{ required: true, trigger: "blur", message: "该项为必填项！" }],
    planContents: [
      { required: true, trigger: "blur", message: "该项为必填项！" }
    ],
    planLevel: [{ required: true, trigger: "blur", message: "该项为必填项！" }],
    planTitle: [{ required: true, trigger: "blur", message: "该项为必填项！" }],
    planType: [{ required: true, trigger: "blur", message: "该项为必填项！" }],
    smsModel: [{ required: true, trigger: "blur", message: "该项为必填项！" }]
  };

  @Provide() loadmap: Boolean = false;
  @Provide() NumberArr: any = [];
  @Provide() NumbersProps: Object = {
    key: "uid",
    label: "userName"
  };
  @Provide() deptsArr: any = [];
  @Provide() editorA: any;
  @Provide() rdeptArr: any = []; //穿梭框value
  @Provide() checkedArr: any = [];
  @Provide() planEventSortArr: any = [];
  @Provide() smsDepartments: any = [];
  //取消事件要在父级取消是所以用到 $emit
  confirmFun(formName: string) {
    let that = this;
    that.creatdeptNumber();
    that.editForm.planContents = that.editorA.getHTML();
    // console.log(that.editForm);
    // return;
    (that as any).$refs[formName].validate((valid: boolean) => {
      if (that.editorA.getText() == false) {
        that.$message.error("没有预案内容！");
        return;
      }
      if (that.rdeptArr.length == 0) {
        that.$message.error("请选择关联部门！");
        return;
      }
      if (valid) {
        (that as any).$axios
          .post("/planInfo/addOrEditPlanInfo", that.editForm)
          .then(() => {
            (that as any).$message({
              message: "操作成功！",
              type: "success"
            });
            (that as any).$emit("dialogFun");
            that.$emit("refreshTableData"); //刷新表格
          });
      } else {
        return false;
      }
    });
  }
  //人员
  getNumberData() {
    let that = this;
    (that as any).$axios
      .get(`/user/getDutyContactsList`)
      .then((res: any) => {
        that.NumberArr = res;
      });
  }
  renderFunc(h: any, option: any) {
    return h(
      "span",
      { domProps: { title: option.userName } },
      option.userName + "-" + option.deptName
    );
  }
  //detail
  getDetailData() {
    let that = this;
    (that as any).$axios
      .get(`/planInfo/getPlanInfoById/${that.id}`)
      .then((res: any) => {
        that.editForm = res;
        if (that.editForm.rdeptInfoList.length > 0) {
          that.editForm.rdeptInfoList.forEach((ele: any) => {
            that.rdeptArr.push(ele.userId);
          });
        }
        that.smsDepartments = that.editForm.smsModelList;
        that.$nextTick(() => {
          that.editorA.setValue(that.editForm.planContents);
        });
      });
  }
  //部门
  getDeptTreeData() {
    let that = this;
    (that as any).$axios
      .get(
        `/dept/getSysDeptList?page=1&size=10000`
      )
      .then((res: any) => {
        that.deptsArr = res.pageData;
      });
  }
    //预案事件分类
    getPlanEventSort() {
        let that = this;
        (that as any).$axios
            .get(
                `/dict/getSysDictByDictTypeCode/event_sort`
            )
            .then((res: any) => {
                that.planEventSortArr = res;
            });
    }
  //创建编辑器
  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();
  }
  //生成关联部门list参数
  creatdeptNumber() {
    let that = this,
      resArr: any = [];
    that.NumberArr.map((ele: any) => {
      if (that.rdeptArr.includes(ele.uid)) {
        let obj = {
          deptId: ele.deptId,
          deptName: ele.deptName,
          email: ele.email,
          mobilePhone: ele.mobliePhone,
          phone: ele.phone,
          userId: ele.uid,
          userName: ele.userName
        };
        this.smsDepartments.forEach((v)=>{
            if(v.deptId == ele.deptId){
                obj.smsModel = v.smsModel;
            }
        });
        resArr.push(obj);
      }
    });
    that.editForm.rdeptInfoList = resArr;
  }
  seletChange(id: any) {
    let that = this,
      arr;
    arr = that.deptsArr.filter((ele: any) => id == ele.id);
    that.editForm.deptName = arr[0].fullName;
  }

  seletChangeplanEventSortArr(dictId: any) {
      let that = this,
          arr;
      arr = that.planEventSortArr.filter((ele: any) => dictId == ele.dictId);
      that.editForm.planType = arr[0].name;
  }

  handleChange(value, direction, movedKeys){
     movedKeys.forEach((v)=>{
         if("right" == direction){
             let isAdd = false;
             this.NumberArr.map((ele: any) => {
                 if (v == ele.uid) {
                     this.smsDepartments.map((e: any)=> {
                         if(e.deptId == ele.deptId ) {
                             e.deptNum++;
                             isAdd = true;
                         };
                     });
                     if(isAdd) return;
                     let obj = {
                         deptId: ele.deptId,
                         deptName: ele.deptName,
                         deptNum: 0
                     };
                     this.smsDepartments.push(obj);
                 }
             });
         }else{
             this.NumberArr.map((ele: any) => {
                 if (v == ele.uid) {
                     this.smsDepartments.map((e: any,index)=> {
                         if(e.deptId == ele.deptId ){
                             if(e.deptNum > 0){
                                 e.deptNum --;
                             }else{
                                 this.smsDepartments =this.smsDepartments.filter(obj=>obj.deptId != ele.deptId);
                             }
                         }
                     });
                 }
             });
         }
     });

  }
  created() {
    let that = this;
    that.editForm.id = that.id;
    that.getNumberData();
    that.getDeptTreeData();
    that.getPlanEventSort();
    that.$nextTick(() => {
        that.creatEditor();
      })
    if(that.id){//编辑
      that.getDetailData();
    }
  }
  mounted() {}

}
</script>