<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">
          <div style="margin-left: 11px;top: -21px;position: relative;">
              <label>选择预案：</label>
              <el-select v-model="relationPlan" placeholder="请选择" @change="seletPlanChange" :disabled="emergencyId!=undefined?true:false">
                  <el-option
                          v-for="item in planArrs"
                          :key="item.id"
                          :label="item.planTitle"
                          :value="item.id"
                  ></el-option>
              </el-select>
              <span style="color: red;" v-if="emergencyId===undefined">（注：请先选择一个预案，为其添加处置方案）</span>
          </div>
        <el-col :span="12" class="flcolum">
          <div v-if="isChangePlan">
            <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-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="emergencyPlanContents">
                <textarea id="editorA" v-model="editForm.planContents"></textarea>
              </el-form-item>
              <el-form-item label="人员列表" prop="personInfo">
                 <el-table :data="editForm.rdeptInfoList" stripe border style="width:100%;" :loading="loading">
                      <el-table-column width="50" type="index" label="序号"></el-table-column>
                      <el-table-column prop="deptName" label="部门"></el-table-column>
                      <el-table-column prop="userName" label="姓名"></el-table-column>
                      <el-table-column prop="phone" label="联系电话"></el-table-column>
                     <el-table-column label="操作" width="100" align="center">
                         <template slot-scope="scope">
                             <el-button type="danger" @click="handleDelete(scope.$index,scope.row)" size="small">
                                 <i class="el-icon-delete"></i> 删除
                             </el-button>
                         </template>
                     </el-table-column>
                  </el-table>
                  <el-button type="primary" size="small" @click="addPersonInfo()">添加人员</el-button>
               </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 v-if="isChangePlan">
            <div class="yatit">预案相关往期案例</div>
              <el-table :data="tableData.pageData" stripe border style="width:100%;" :loading="loading">
                  <el-table-column width="50" type="index" label="序号"></el-table-column>
                  <el-table-column prop="eventName" label="事件名称"></el-table-column>
                  <el-table-column prop="eventLevel" label="事件等级">
                      <template slot-scope="scope">
                          <font>{{scope.row.eventLevel + '级'}}</font>
                      </template>
                  </el-table-column>
                  <el-table-column prop="eventType" label="事件类型"></el-table-column>
                  <el-table-column label="操作" width="150" align="center">
                      <template slot-scope="scope">
                          <el-button type="primary" @click="resoveFun(scope.row)" size="small" plain>
                              <i class="el-icon-edit"></i> 事件详情
                          </el-button>
                      </template>
                  </el-table-column>
              </el-table>
              <el-pagination
                      background
                      layout="total,sizes, prev, pager, next, jumper"
                      :total="tableData.total"
                      @size-change="handleSizeChange"
                      @current-change="handleCurrentChange"
                      :current-page="PAGE.page"
                      :page-size="PAGE.size"
                      v-if="isChangePlan"
              ></el-pagination>
          </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>
        <EventDetailView
                v-if="reVisible"
                :reVisible="reVisible"
                :eventId="formData.id"
                :eventStatus="formData.eventStatus"
                @redialogFun="recloseDialog"
        ></EventDetailView>
        <AddPersonInfo
                v-if="addPerson"
                :reVisible="addPerson"
                :rdeptInfoList="editForm.rdeptInfoList"
                @redialogFun="recloseAddPersonInfo"
                @addNewPersonToArr="addNewPersonToArr"
                @getNumberData="getNumberData"
        ></AddPersonInfo>
    </el-dialog>
  </div>
</template>
<style lang="scss">
  .w100 .el-dialog {
    width: 80%;
    .flcolum {
      > div {
        border-radius: 3px;
      }
    }
    .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 EventDetailView from "./EventDetailView.vue";
    import AddPersonInfo from "./AddPersonInfo.vue";
    import METHOD from "@/utils/methods";
    @Component({
        components: { City ,EventDetailView,AddPersonInfo}
    })
    export default class DealwithNecessaryEdit extends Vue {
        // @Getter('signs') signsData: any;
        //属性或参数中使用!:表示强制解析（告诉typescript编译器，这里一定有值），常用于vue-decorator中的@Prop
        @Prop(Boolean) dialogVisible!: Boolean;
        @Prop(String) title!: String;
        @Prop(String) emergencyId!: String;
        @Provide() tableData: Object = { pageData: [], total: 0 };
        @Provide() PAGE: any = { page: 1, size: 10 };
        @Provide() searchData: any = { eventStatus:"4"};
        @Provide() loading: Boolean = false;
        @Provide() relationPlan: any="";
        @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() formData: Object = {};
        @Provide() reVisible: Boolean = false;
        @Provide() addPerson: Boolean = false;
        @Provide() isChangePlan: Boolean = false;
        @Provide() planArrs: any = [];
        @Provide() planId: any = "";
        @Provide() count: any = 0;
        //取消事件要在父级取消是所以用到 $emit
        confirmFun(formName: string) {
            let that = this;
            that.editForm.planContents = that.editorA.getHTML();
            that.editForm.emergencyPlanTitle = that.editForm.planTitle;
            that.editForm.emergencyPlanType = that.editForm.planType;
            that.editForm.emergencyPlanLevel = that.editForm.planLevel;
            that.editForm.emergencyPlanContents = that.editForm.planContents;
            that.editForm.emergencySmsModel = that.editForm.smsModel;
            that.editForm.relationPlanId = that.editForm.id;
            (that as any).$refs[formName].validate((valid: boolean) => {
                if (that.editorA.getText() == false) {
                    that.$message.error("没有方案内容！");
                    return;
                }
                if (valid) {
                    (that as any).$axios
                        .post("/emergencyPlan/addOrEditEmergencyPlanInfo", that.editForm)
                        .then(() => {
                            (that as any).$message({
                                message: "操作成功！",
                                type: "success"
                            });
                            (that as any).$emit("dialogFun");
                            that.$emit("refreshTableData"); //刷新表格
                        });
                } else {
                    return false;
                }
            });
        }
        //人员
        getNumberData(arrys) {
            this.NumberArr = arrys;
        }
        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.planId}`)
                .then((res: any) => {
                    that.editForm = res;
                    if (that.editForm.rdeptInfoList.length > 0) {
                        that.editForm.rdeptInfoList.forEach((ele: any) => {
                            that.rdeptArr.push(ele.userId);
                        });
                    }
                    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();
        }

        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;
        }
        getEventInfoList() {
            let that = this,
                params = Object.assign(that.searchData);
            that.loading = true;
            (that as any).$axios
                .post("/eventInfo/getEventInfoList", params)
                .then((res: any) => {
                    that.loading = false;
                    if( res ) that.tableData = res;
                });
        }
        resoveFun(row: any) {
            this.reVisible = true;
            this.formData = Object.assign({}, row);
        }
        recloseDialog() {
            this.reVisible = false;
        }
        getPlanArrs() {
            let that = this;
            (that as any).$axios
                .post(`/planInfo/getAllPlanInfoList`,{})
                .then((res: any) => {
                    that.planArrs = res;
                });
        }
        seletPlanChange(id: any) {
            let that = this,
                arr;
            arr = that.planArrs.filter((ele: any) => id == ele.id);
            that.editForm.planTitle = arr[0].planTitle;
            that.planId = arr[0].id;
            that.searchData.eventLevel = arr[0].planLevel;
            that.isChangePlan = true;
            that.getEventInfoList();
            that.getDetailData();
            if(that.count==0){
                that.$nextTick(() => {
                    that.creatEditor();
                })
            }
            that.count++;
        }
        handleSizeChange(val: any) {
            this.PAGE.size = val;
            this.getEventInfoList();
        }
        handleCurrentChange(val: any) {
            this.PAGE.page = val;
            this.getEventInfoList();
        }
        addPersonInfo(){
            this.addPerson = true;
        }
        recloseAddPersonInfo() {
            this.addPerson = false;
        }
        addNewPersonToArr(arry){
            for(var i=0;i<arry.length;i++){
                this.editForm.rdeptInfoList.push(arry[i])
            }
        }
        handleDelete(index) {
            this.editForm.rdeptInfoList.splice(index,1)
        }
        getEmergencyPlanInfoById(){
            let that = this;
            (that as any).$axios
                .get(`/emergencyPlan/getEmergencyPlanInfoById/${that.emergencyId}`)
                .then((res: any) => {
                    that.editForm = res;
                    that.$set(that.editForm, "planTitle", that.editForm.emergencyPlanTitle);
                    that.$set(that.editForm, "planType", that.editForm.emergencyPlanType)
                    that.$set(that.editForm, "planLevel", that.editForm.emergencyPlanLevel)
                    that.$set(that.editForm, "planContents", that.editForm.emergencyPlanContents)
                    that.$set(that.editForm, "smsModel", that.editForm.emergencySmsModel)
                    that.relationPlan= that.editForm.relationPlan;
                    that.searchData.eventLevel = that.editForm.emergencyPlanLevel;
                    if (that.editForm.rdeptInfoList.length > 0) {
                        that.editForm.rdeptInfoList.forEach((ele: any) => {
                            that.rdeptArr.push(ele.userId);
                        });
                    }
                    if(that.count==0){
                        that.$nextTick(() => {
                            that.creatEditor();
                        })
                    }
                    that.$nextTick(() => {
                        that.editorA.setValue(that.editForm.planContents);
                    });
                    that.getEventInfoList();
                    that.count++;
                });
        }
        created() {
            let that = this;
            that.getDeptTreeData();
            that.getPlanArrs();
            that.getPlanEventSort();
            if(this.emergencyId){
                that.getEmergencyPlanInfoById();
                that.isChangePlan = true;
            }

        }
        mounted() {}

    }
</script>