<template>
  <div slot="content" class="bgColor newIncident">
    <div class="header">新建事件</div>
    <div class="navBar">
      <div class="fl">
        <a
          :class="{ active: label == 'incidentInfo' }"
          href="javascript:;"
          @click="toInfo('incidentInfo')"
          >事件信息</a
        >
      </div>
      <div class="fl">
        <a
          :class="{ active: label == 'handlerInfo' }"
          href="javascript:;"
          @click="toInfo('handlerInfo')"
          >处理信息</a
        >
      </div>
    </div>
    <div class="label" id="incidentInfo">事件信息</div>
    <cube-form
      :model="model"
      @validate="validateHandler"
      @submit.prevent="submitHandler"
    >
      <cube-form-group>
        <cube-form-item
          :field="fields[20]"
          v-if="valConfig == 2"
          class="btn_plcaeholde btn_local"
        >
          <!-- <cube-button @click="showPlacePicker()">{{selectedPlaceTxt?selectedPlaceTxt:'请输入故障地点'}}</cube-button> -->
          <input
            type="text"
            class="inp_local"
            placeholder="请输入报修科室"
            v-model="deptInpVal"
            @input="changeDeptList()"
            @click="showDeptPicker()"
          />
        </cube-form-item>
        <cube-form-item
          v-if="valConfig == 1"
          :field="fields[0]"
        ></cube-form-item>
        <cube-form-item
          v-if="valConfig == 2"
          :field="fields[21]"
        ></cube-form-item>
        <cube-form-item :field="fields[1]"></cube-form-item>
        <cube-form-item :field="fields[2]" class="btn_plcaeholde">
          <cube-button @click="showPlacePicker()">{{
            selectedPlaceTxt ? selectedPlaceTxt : "请选择区域地点"
          }}</cube-button>
        </cube-form-item>
        <!-- 故障地点： -->
        <!-- <cube-form-item :field="fields[19]" class="btn_plcaeholde btn_local"> -->
        <!-- <cube-button @click="showPlacePicker()">{{selectedPlaceTxt?selectedPlaceTxt:'请输入故障地点'}}</cube-button> -->
        <!-- <input
            type="text"
            class="inp_local"
            placeholder="请输入故障地点"
            v-model="inpLocalVal"
            @input="changeLocalList()"
            @click="showPlacePicker()"
          />
        </cube-form-item> -->
        <cube-form-item :field="fields[3]"></cube-form-item>
        <cube-form-item :field="fields[4]" class="btn_plcaeholde">
          <cube-button @click="showCategoryPicker()">{{
            selectedCategoryTxt ? selectedCategoryTxt : "请选择事件分类"
          }}</cube-button>
        </cube-form-item>
        <cube-form-item
          :field="fields[5]"
          class="btn_plcaeholde"
        ></cube-form-item>
        <!-- <cube-form-item :field="fields[6]" class="btn_plcaeholde incidentTitle">
          <div class="titleRefer">
            <textarea
              class="titleTxtArea fl"
              placeholder="请输入事件主题"
              v-model="incidentTitle"
              @input="inpTitle()"
            ></textarea>
            <span class="abtn fl" @click="referKnowledge()">引入知识库</span>
          </div>
        </cube-form-item>-->
        <cube-form-item :field="fields[7]"></cube-form-item>
        <div class="label formLabel">
          报修图片
          <span>(最多可上传3张JPG或PNG,每张不能超过10M)</span>
        </div>
        <div class="uplod">
          <cube-upload
            ref="upload"
            :max="3"
            :action="action"
            :simultaneous-uploads="3"
            @files-added="filesAdded"
            @file-submitted="fileSubmitted"
          />
        </div>
        <!-- <cube-form-item :field="fields[8]" class="btn_plcaeholde"></cube-form-item>
        <cube-form-item :field="fields[9]" class="btn_plcaeholde"></cube-form-item>-->
        <cube-form-item
          :field="fields[10]"
          class="btn_plcaeholde"
        ></cube-form-item>
        <div class="zc" v-if="wxIncidentWithCmdb == 1">
          <cube-form-item
            :field="fields[22]"
            class="btn_plcaeholde zc-item"
          ></cube-form-item>
          <span class="icon dash dash-saoyisao zc-sao" @click="scan()"></span>
        </div>
        <div class="label" id="handlerInfo">处理信息</div>
        <div class="handleRadio">
          <cube-radio-group
            v-model="order"
            :options="handleTypes"
            position="right"
            :hollow-style="true"
          />
        </div>
        <!-- 直接处理 begin -->
        <cube-form-item
          v-if="order == 1"
          :field="fields[11]"
          class="btn_plcaeholde"
        ></cube-form-item>
        <cube-form-item
          v-if="order == 1"
          :field="fields[12]"
          class="btn_plcaeholde"
        ></cube-form-item>
        <cube-form-item
          v-if="order == 1"
          :field="fields[13]"
          class="btn_plcaeholde"
        ></cube-form-item>
        <div v-if="order == 1" class="label formLabel">
          报修图片
          <span>(最多可上传3张JPG或PNG,每张不能超过10M)</span>
        </div>
        <div class="uplod" v-if="order == 1">
          <cube-upload
            ref="upload1"
            :max="3"
            :action="action1"
            :simultaneous-uploads="3"
            @files-added="filesAdded1"
            @file-submitted="fileSubmitted1"
          />
        </div>
        <cube-form-item v-if="order == 1" :field="fields[14]"></cube-form-item>
        <cube-form-item
          v-if="order == 1 && model.knowledge == true"
          :field="fields[15]"
          class="btn_plcaeholde"
        ></cube-form-item>
        <!-- 直接处理 end -->

        <!-- 派单 begin -->
        <cube-form-item v-if="order == 2" :field="fields[16]"></cube-form-item>
        <cube-form-item
          v-if="order == 2 && model.handleUserOrGroup == true"
          :field="fields[17]"
          class="btn_plcaeholde"
        ></cube-form-item>
        <cube-form-item
          v-if="order == 2 && model.handleUserOrGroup == false"
          :field="fields[18]"
          class="btn_plcaeholde"
        ></cube-form-item>
        <!-- 派单 end -->
      </cube-form-group>
      <cube-form-group class="sub">
        <cube-button type="submit" @click="subVali()">提交</cube-button>
      </cube-form-group>
    </cube-form>
    <load-ing v-show="loadShow"></load-ing>
    <promp-ting
      :conents="promptingConent"
      :status="promptingStatus"
    ></promp-ting>
  </div>
</template>
<script>
import CubePage from "./../components/cube-page.vue";
import CubeButtonGroup from "./../components/cube-button-group.vue";
import DatePicker from "./../components/date-picker.vue";
import CubeExtendPopup from "./../components/extend-popup.vue";
import LoadIng from "./../views/loading.vue";
import PrompTing from "./../views/prompting.vue";
import { SM } from "./../http/http";
// import host from "../request/host";
// 知识库类型
const solution = {
  props: {
    value: {
      default() {
        return [];
      },
    },
  },
  data() {
    return {
      selected: [],
      selectData: [],
      initVal: JSON.parse(localStorage.getItem("solution")) || [0, 0, 0],
      allPlace: {}, //存放请求到的所有区域地点
      sleectHouseNumber: {}, //区域地点
      initSjList: [], //原始事件列表
      selectedIndex: [0, 0],
      selectedIndexCate: [0, 0, 0],
    };
  },
  render(createElement) {
    return createElement(
      "cube-button",
      {
        on: {
          click: this.showPicker,
        },
      },
      this.selected.length
        ? this.selected[this.selected.length - 1]
        : "请选择知识库类型"
    );
  },
  created() {
    this.getTree();
  },
  mounted() {},
  methods: {
    showPicker() {
      this.picker.show();
    },
    selectHandler(selectedVal, selectedIndex, selectedTxt) {
      var selected = [];
      selectedTxt.forEach(function (v, i) {
        if (v != "") {
          selected.push(v);
        }
      });
      this.selected = selected;
      this.$emit("input", selectedVal);
      localStorage.setItem("solution", JSON.stringify(selectedIndex));
    },
    // 获取事件分类数据
    getTree() {
      let that = this;
      that.$http
        .post("/service/solution/fetchDataList/solutionType", {
          idx: 0,
          sum: 100,
        })
        .then(function (res) {
          // console.log(res);
          var list = res.data.list;
          var tree = [];
          list.forEach((v, i) => {
            if (!v.parent) {
              tree[i] = {
                value: v.id,
                text: v.typeName,
                children: [],
              };
            } else {
              tree.forEach((val, idx) => {
                if (
                  v.parent &&
                  !v.parent.parent &&
                  val.text == v.parent.typeName
                ) {
                  tree[idx].children.push({
                    value: v.id,
                    text: v.typeName,
                    children: [],
                  });
                } else if (v.parent.parent) {
                  tree[idx].children.forEach((value, index) => {
                    if (value.text == v.parent.typeName) {
                      tree[idx].children[index].children.push({
                        value: v.id,
                        text: v.typeName,
                      });
                    }
                  });
                }
              });
            }
          });
          var arrTree = [];
          tree.forEach(function (v) {
            arrTree.push(v);
          });
          that.selectData = arrTree;
          console.log(arrTree);

          that.picker = that.$createCascadePicker({
            title: "知识库类型选择",
            data: that.selectData,
            selectedIndex: that.initVal,
            onSelect: that.selectHandler,
          });
        });
    },
  },
};

export default {
  data() {
    return {
      validity: {},

      valid: undefined,
      action: {
        target:
          this.$host + "/service/common/common/uploadAttachment/incident/",
        data: {},
      },
      action1: {
        target:
          this.$host + "/service/common/common/uploadAttachment/incident/",
        data: {},
      },
      isUploading: false,
      loadShow: false,
      incidentWithConsumable: localStorage.getItem("incidentWithConsumable"), //是否绑定耗材
      wxIncidentWithCmdb: localStorage.getItem("wxIncidentWithCmdb"), //是否绑定资产
      loginUser: JSON.parse(localStorage.getItem("loginUser")),
      valConfig: JSON.parse(localStorage.getItem("valConfig")) - 0, //报修主体
      name: "",
      phone: "",
      label: "incidentInfo", //顶部快速定位
      modelData: {
        incident: {},
      }, //上传的model
      timer: null,
      incidentTitle: "", //事件主题
      referenceInfo: {}, //引用信息
      placeSelectData: [], //区域地点下拉框选项
      inpLocalVal: "", //故障地点输入框
      faultLocationList: [], //区域地点拼接下拉框选项
      deptInpVal: "", //报修科室输入框
      deptList: [], //报修科室下拉选项
      deptRes: "", //下拉框科室信息
      model: {
        contactsInformation: "",
        placeValue: [],
        address: "", //故障地点
        requester: "", //报修科室
        houseNumber: "", //详细地址
        description: "", //事件描述
        // bxcode: "",
        assetId: "", //资产
        category: [],
        source: "", //事件来源
        title: "", //事件主题
        priority: "", //优先级
        emergency: "", //紧急度
        influence: "", //影响度
        handleCategory: "", //处理方式
        closecode: "", //关闭代码
        handleDescription: "", //处理方案
        knowledge: false, //是否提交知识库
        handlerUser: "", //处理人
        candidateGroups: "", //处理组
        solutionType: [], //知识库类型
        handleUserOrGroup: false, //处理人or处理组
      },
      selectedCategoryTxt: "", //事件分类选中展示
      selectedPlaceTxt: "", //区域地点选中展示
      // showPrompting:false,
      promptingConent: "",
      promptingStatus: "",
      order: 1, //处理方式  1：直接处理，2:派单
      sourceArr: [], //事件来源数组
      priorityArr: [], //优先级数组
      emergencyArr: [], //紧急度数组
      influenceArr: [], //影响度数组
      handleCategoryArr: [], //处理方式数组
      closecodeArr: [], //关闭代码数组
      handlerUserArr: [], //处理人数组
      candidateGroupsArr: [], //处理组数组
      handleTypes: [
        {
          label: "直接处理",
          value: 1,
        },
        {
          label: "派单",
          value: 2,
        },
      ],
      vali: false,
      fields: [
        {
          type: "input",
          modelKey: "contacts",
          label: "联系人:",
          props: {
            placeholder: "请输入联系人",
          },
          rules: {
            required: true,
          },
        },
        {
          type: "input",
          modelKey: "contactsInformation",
          label: "联系电话:",
          props: {
            placeholder: "请输入联系电话",
          },
          rules: {
            required: true,
          },
        },
        {
          component: "button",
          modelKey: "placeValue",
          label: "区域地点:",
          rules: {
            required: false,
          },
          messages: {
            required: "请选择区域地点",
          },
        },
        {
          type: "textarea",
          modelKey: "houseNumber",
          label: "详细地址:",
          props: {
            placeholder: "请输入详细地址",
          },
          rules: {
            required: false,
          },
          debounce: 100,
        },
        {
          component: "button",
          modelKey: "category",
          label: "事件分类:",
          rules: {
            required: true,
          },
          // messages: {
          //   required: "请选择事件分类"
          // }
        },
        {
          type: "select",
          modelKey: "source",
          label: "事件来源:",
          props: {
            options: this.sourceArr,
            title: "请选择事件来源",
            placeholder: "请选择事件来源",
          },
          rules: {
            required: true,
          },
        },
        {
          // component: Place,
          type: "input",
          modelKey: "title",
          label: "事件主题:",
          rules: {
            required: true,
          },
          messages: {
            required: "请选择事件主题",
          },
        },
        {
          type: "textarea",
          modelKey: "description",
          label: "事件描述:",
          props: {
            placeholder: "请详细描述故障，并上传故障图片，例如：网络故障。",
          },
          rules: {
            required: true,
          },
          debounce: 100,
        },
        {
          type: "select",
          modelKey: "influence",
          label: "影响度:",
          props: {
            options: this.influenceArr,
            title: "请选择影响度",
            placeholder: "请选择影响度",
          },
          rules: {
            required: false,
          },
          events: {
            change: (value, index, text) => {
              console.log(value, index, text);
              console.log(this.model);
              var that = this;
              if (this.model.emergency) {
                this.$http
                  .post("/service/bpm/data/fetchDataList/prioritymatrix", {
                    idx: 0,
                    sum: 1000,
                    prioritymatrix: {
                      emergency: { id: this.model.emergency },
                      influence: { id: this.model.influence },
                    },
                  })
                  .then(function (res) {
                    if (res.data.list.length) {
                      that.model.priority = res.data.list[0].priority.id;
                    }
                  });
              }
            },
          },
        },
        {
          type: "select",
          modelKey: "emergency",
          label: "紧急度:",
          props: {
            options: this.emergencyArr,
            title: "请选择紧急度",
            placeholder: "请选择紧急度",
          },
          rules: {
            required: false,
          },
          events: {
            change: (value, index, text) => {
              console.log(value, index, text);
              console.log(this.model);
              var that = this;
              if (this.model.influence) {
                this.$http
                  .post("/service/bpm/data/fetchDataList/prioritymatrix", {
                    idx: 0,
                    sum: 1000,
                    prioritymatrix: {
                      emergency: { id: this.model.emergency },
                      influence: { id: this.model.influence },
                    },
                  })
                  .then(function (res) {
                    console.log(res.data);
                    if (res.data.list.length) {
                      that.model.priority = res.data.list[0].priority.id;
                    }
                  });
              }
            },
          },
        },
        {
          type: "select",
          modelKey: "priority",
          label: "优先级:",
          props: {
            options: this.priorityArr,
            title: "请选择优先级",
            placeholder: "请选择优先级",
          },
          rules: {
            required: true,
          },
        },
        {
          type: "select",
          modelKey: "handleCategory",
          label: "处理方式:",
          props: {
            options: this.handleCategoryArr,
            title: "请选择处理方式",
            placeholder: "请选择处理方式",
          },
          rules: {
            required: true,
          },
        },
        {
          type: "select",
          modelKey: "closecode",
          label: "关闭代码:",
          props: {
            options: this.closecodeArr,
            title: "请选择关闭代码",
            placeholder: "请选择关闭代码",
          },
          rules: {
            required: true,
          },
        },
        {
          type: "textarea",
          modelKey: "handleDescription",
          label: "处理方案:",
          props: {
            placeholder: "请填写处理方案",
          },
          rules: {
            required: true,
          },
          debounce: 100,
        },
        {
          type: "switch",
          modelKey: "knowledge",
          label: "是否提交知识库:",
          rules: {
            required: false,
          },
        },
        {
          component: solution,
          modelKey: "solutionType",
          label: "知识库类型:",
          rules: {
            required: true,
          },
          messages: {
            required: "",
          },
        },
        {
          type: "switch",
          modelKey: "handleUserOrGroup",
          label: "是否选择处理人:",
          rules: {
            required: false,
          },
        },
        {
          type: "select",
          modelKey: "handlerUser",
          label: "处理人:",
          props: {
            options: this.handlerUserArr,
            title: "请选择处理人",
            placeholder: "请选择处理人",
          },
          rules: {
            required: true,
          },
        },
        {
          type: "select",
          modelKey: "candidateGroups",
          label: "处理组:",
          props: {
            options: this.candidateGroupsArr,
            title: "请选择处理组",
            placeholder: "请选择处理组",
          },
          rules: {
            required: true,
          },
        },
        {
          type: "select",
          modelKey: "address",
          label: "故障地点:",
          props: {
            options: this.faultLocationList,
            title: "请选择故障地点",
            placeholder: "请选择故障地点",
          },
          rules: {
            required: true,
          },
        },
        {
          type: "select",
          modelKey: "requester",
          label: "报修科室:",
          props: {
            options: this.requesterList,
            title: "请选择报修科室",
            placeholder: "请选择报修科室",
          },
          rules: {
            required: true,
          },
        },
        {
          type: "input",
          modelKey: "contacts",
          label: "联系人:",
          props: {
            placeholder: "请输入联系人",
          },
          rules: {
            required: false,
          },
        },
        {
          type: "input",
          modelKey: "assetId",
          label: "资产:",
          rules: {
            required: false,
          },
          props: {
            placeholder: "请选择资产",
            disabled: true,
          },
        },
      ],
    };
  },
  watch: {
    // "model.category": {
    //   deep: true,
    //   handler: function(n, o) {
    //     this.model.houseNumber = houseNumber;
    //     console.log(this.model.houseNumber);
    //   }
    // }
  },
  methods: {
    //扫资产
    scan(){
      SM(this).then((ress1) => {
        this.model.assetId = ress1;
      })
    },
    // 输入事件描述
    inpTitle() {
      this.model.title = this.incidentTitle;
    },

    // 快速定位
    toInfo(id) {
      this.label = id;
      $("body,html").animate(
        {
          scrollTop:
            $("#" + id).offset().top -
            $(".header")[0].offsetHeight -
            $(".navBar")[0].offsetHeight,
        },
        260
      );
    },
    subVali() {
      this.vali = true;
    },
    // 获取事件单号
    getsjnum() {
      var that = this;
      this.$http.get("/service/bpm/bpm/restful/sj", {}).then(function (res) {
        that.modelData.incident.incidentsign = res.data.data;
      });
    },
    // 获取事件来源
    getSource() {
      var that = this;
      this.$http
        .post("/service/common/common/getDictionary", {
          key: "incident_source",
          type: "list",
        })
        .then(function (res) {
          res.data.forEach(function (v, i) {
            that.sourceArr.push({
              text: v.name,
              value: v.id,
            });
          });
          that.fields[5].props.options = that.sourceArr;
        });
    },
    // 获取优先级
    getPriority() {
      var that = this;
      this.$http
        .post("/service/common/common/getDictionary", {
          key: "incident_priority",
          type: "list",
        })
        .then(function (res) {
          res.data.forEach(function (v, i) {
            that.priorityArr.push({
              text: v.name,
              value: v.id,
            });
          });
          that.fields[10].props.options = that.priorityArr;
        });
    },
    // 获取紧急度
    getMergency() {
      var that = this;
      this.$http
        .post("/service/common/common/getDictionary", {
          key: "incident_emergency",
          type: "list",
        })
        .then(function (res) {
          res.data.forEach(function (v, i) {
            that.emergencyArr.push({
              text: v.name,
              value: v.id,
            });
          });
          that.fields[9].props.options = that.emergencyArr;
        });
    },
    // 获取影响度
    getInfluence() {
      var that = this;
      this.$http
        .post("/service/common/common/getDictionary", {
          key: "incident_influence",
          type: "list",
        })
        .then(function (res) {
          res.data.forEach(function (v, i) {
            that.influenceArr.push({
              text: v.name,
              value: v.id,
            });
          });
          that.fields[8].props.options = that.influenceArr;
        });
    },
    // 获取处理方式
    getHandleCategory() {
      var that = this;
      this.$http
        .post("/service/common/common/getDictionary", {
          key: "incident_handleCategory",
          type: "list",
        })
        .then(function (res) {
          res.data.forEach(function (v, i) {
            that.handleCategoryArr.push({
              text: v.name,
              value: v.id,
            });
          });
          that.fields[11].props.options = that.handleCategoryArr;
        });
    },
    // 获取关闭代码
    getClosecode() {
      var that = this;
      this.$http
        .post("/service/common/common/getDictionary", {
          key: "incident_closecode",
          type: "list",
        })
        .then(function (res) {
          res.data.forEach(function (v, i) {
            that.closecodeArr.push({
              text: v.desc,
              value: v.id,
            });
          });
          that.fields[12].props.options = that.closecodeArr;
        });
    },
    // 获取处理人
    getHandlerUser() {
      var that = this;
      this.$http
        .post("/service/user/data/fetchDataList/user", {
          idx: 0,
          sum: 1000,
          user: {
            roledata: { rolecode: "first-line support" },
            selectType: "1",
          },
        })
        .then(function (res) {
          res.data.list.forEach(function (v, i) {
            that.handlerUserArr.push({
              text: v.name,
              value: v.id,
            });
          });
          that.fields[17].props.options = that.handlerUserArr;
        });
    },
    // 获取处理组
    getCandidateGroups() {
      var that = this;
      this.$http
        .post("/service/user/data/fetchDataList/group", {
          idx: 0,
          sum: 1000,
          group: { selectType: "nouser" },
        })
        .then(function (res) {
          res.data.list.forEach(function (v, i) {
            that.candidateGroupsArr.push({
              text: v.groupName,
              value: v.id,
            });
          });
          that.fields[18].props.options = that.candidateGroupsArr;
        });
    },
    // 暂时存值
    setLocalStroageData() {
      var that = this;
      var a1 = [],
        a2 = [],
        category = [],
        solutionType = [];
      that.model.category.forEach(function (v, i) {
        if (v) {
          a1.push(v);
        }
      });
      category = a1;
      that.model.solutionType.forEach(function (v, i) {
        if (v) {
          a2.push(v);
        }
      });
      solutionType = a2;
      if (that.model.placeValue.length == 2) {
        that.model.areaId =
          that.model.placeValue[that.model.placeValue.length - 2];
        that.model.placeId =
          that.model.placeValue[that.model.placeValue.length - 1];
      } else if (that.model.placeValue.length == 1) {
        that.model.areaId =
          that.model.placeValue[that.model.placeValue.length - 1];
        that.model.placeId = "";
      }

      // that.modelData.incident.houseNumber = that.model.address[0];
      that.modelData.incident["repairType"] = that.valConfig;
      if (that.valConfig == 1) {
        // that.modelData.incident.requester = that.loginUser;
        // that.modelData.incident.account = that.loginUser.account;
        // that.modelData.requestershow = that.loginUser;
      } else if (that.valConfig == 2) {
        that.modelData.incident.department = that.model.requester;
      }
      if (that.wxIncidentWithCmdb == 1) {
        that.modelData.incident.assetId = that.model.assetId;
      }
      that.modelData.incident.area = { id: that.model.areaId };
      that.modelData.incident.place = { id: that.model.placeId };
      that.modelData.incident.category = {
        id: category[category.length - 1],
      };
      that.modelData.initUser = that.loginUser.id;
      that.modelData.loginUser = that.loginUser;
      that.modelData.fromWeChat = true;
      that.modelData.incident.contactsInformation =
        that.model.contactsInformation;
      that.modelData.incident.contacts = that.model.contacts;
      that.modelData.incident.houseNumber = that.model.houseNumber;
      that.modelData.incident.acceptUser = that.loginUser;
      that.modelData.incident.requester = {};
      that.modelData.incident.handlingPersonnelUser = { id: that.loginUser.id };
      that.modelData.incident.source = { id: that.model.source };
      that.modelData.incident.title = that.model.title;
      that.modelData.incident.description = that.model.description;
      // that.modelData.incident.emergency = { id: that.model.emergency };
      // that.modelData.incident.influence = { id: that.model.influence };
      that.modelData.incident.priority = { id: that.model.priority };
      that.modelData.incident.alarmType = false;
      if (that.order == 1) {
        // 直接处理
        that.modelData.handler_code = "resolve";
        that.modelData.start_code = "close";
        that.modelData.incident.directProcess = 1;
        that.modelData.incident.handleDescription =
          that.model.handleDescription;
        that.modelData.incident.handleCategory = {
          id: that.model.handleCategory,
        };
        that.modelData.incident.closecode = { id: that.model.closecode };
        that.modelData.bpm_activiti = {
          solutionType: {
            id: solutionType[solutionType.length - 1],
          },
        };
        that.modelData.isSolution = that.model.knowledge;
      } else if (that.order == 2) {
        // 派单
        that.modelData.start_code = "assignment";
        if (that.model.handleUserOrGroup) {
          // 处理人
          that.modelData.assignee = that.model.handlerUser;
          that.modelData.incident.handlingPersonnelUser = {
            id: that.model.handlerUser,
          };
        } else {
          // 处理组
          that.modelData.candidateGroups = that.model.candidateGroups;
          if (that.modelData.assignee) {
            delete that.modelData.assignee;
          }
          if (that.modelData.incident.handlerUser) {
            delete that.modelData.incident.handlerUser;
          }
        }

        if (that.modelData.incident.handlingPersonnelUser) {
          delete that.modelData.incident.handlingPersonnelUser;
        }
        if (that.modelData.incident.handleDescription) {
          delete that.modelData.incident.handleDescription;
        }
        if (that.modelData.incident.closecode) {
          delete that.modelData.incident.closecode;
        }
        if (that.modelData.incident.degree) {
          delete that.modelData.incident.degree;
        }
        if (that.modelData.isSolution) {
          delete that.modelData.isSolution;
        }
      }

      console.log(that.modelData);

      that.model.fileUrl = "url";
      that.loadShow = true;
    },
    // 事件主题引入知识库
    // referKnowledge() {
    //   var that = this;
    //   if (!that.model.title) return;
    //   that.setLocalStroageData();
    //   localStorage.setItem("modelData", JSON.stringify(that.modelData));
    //   localStorage.setItem("model", JSON.stringify(that.model));
    //   localStorage.setItem("order", that.order);

    //   this.$router.push({
    //     name: "ReferenceList",
    //     params: { data: that.model.title }
    //   });
    // },
    // 获取页面数据
    getMessage() {
      var that = this;
      console.log(that.$route.params.data, "params");
      if (that.$route.params.data) {
        var inspecInfo = that.$route.params.data;
        // 生成事件
        if (that.wxIncidentWithCmdb == 1) {
          that.model.assetId = inspecInfo.assetId;
        }
        that.model.contacts = inspecInfo.requester.name;
        that.model.contactsInformation = inspecInfo.requester.mphone
          ? inspecInfo.requester.mphone
          : "";
        // that.order = 2;
        // that.model.handleUserOrGroup = true;
        that.model.source = 1549;
        that.model.description = inspecInfo.incidentDescription; //caca
        that.model.houseNumber = inspecInfo.address; //caca

        if (inspecInfo.place) {
          if (inspecInfo.place.id) {
            that.model.placeValue[0] = inspecInfo.place.area.id;
            that.model.placeValue[1] = inspecInfo.place.id;
            that.selectedPlaceTxt =
              inspecInfo.place.area.area + " " + inspecInfo.place.place;
          }
        }
      } else {
        that.name = that.loginUser.name;
        that.model.contactsInformation = that.loginUser.phone;
        that.model.contacts = that.loginUser.name;
        that.model.houseNumber = that.loginUser.houseNumber;
        if (that.loginUser.place && that.loginUser.place.length) {
          if (that.loginUser.place.id) {
            if (that.loginUser.place.area) {
              that.model.placeValue[0] = that.loginUser.place.area.id;
            }
            that.model.placeValue[1] = that.loginUser.place.id;
          }
        }
        // if (localStorage.getItem("model")) {
        //   that.model = JSON.parse(localStorage.getItem("model"));
        //   that.incidentTitle = that.model.title;
        // }
        // if (localStorage.getItem("modelData")) {
        //   that.modelData = JSON.parse(localStorage.getItem("modelData"));
        // }
        // if (localStorage.getItem("referenceInfo")) {
        //   that.referenceInfo = JSON.parse(localStorage.getItem("referenceInfo"));
        //   that.incidentTitle = that.model.title = that.referenceInfo.title;
        //   that.model.handleDescription = that.referenceInfo.content;
        // }
        // if (localStorage.getItem("order")) {
        //   that.order = localStorage.getItem("order") - 0;
        // }
      }
    },
    // 提交
    submitHandler() {
      $("#fade").fadeOut();
      var that = this;
      that.setLocalStroageData();
      if (that.selectHouseNumber && that.selectHouseNumber.place) {
        that.modelData.incident.place = that.selectHouseNumber;
      }
      console.log(
        that.modelData,
        that.selectHouseNumber,
        "2020年4月25日14:09:29"
      );
      //服务台生成事件
      if (this.$route.params.data && this.$route.params.data.id) {
        that.modelData.flow = this.$route.params.data.id;
      }
      that.$http
        .post("/service/bpm/bpm/start/bpm_incident", that.modelData)
        .then(function (res) {
          if (res.data) {
            that.action.target = that.action.target + res.data.id;
            that.action1.target = that.action1.target + res.data.id;
            setTimeout(function () {
              that.$refs.upload.start();
              if (that.order == 1) {
                that.$refs.upload1.start();
              }
            }, 100);
            $("#fade").fadeIn();
            that.promptingConent = "恭喜您,新建报修成功!";
            that.promptingStatus = true;
            that.dialog = that
              .$createDialog({
                type: "alert",
                title: "新建成功",
                content: "点击返回首页",
                icon: "cubeic-right",
                onConfirm: (e, promptValue) => {
                  that.$router.push({ path: "/main" });
                },
              })
              .show();
            localStorage.removeItem("category");
            localStorage.removeItem("model");
            localStorage.removeItem("modelData");
            localStorage.removeItem("placeIndex");
            localStorage.removeItem("referenceInfo");
            localStorage.removeItem("solution");
            localStorage.removeItem("order");
            setTimeout(function () {
              $("#fade").fadeOut();
            }, 2000);
          } else {
            $("#fade").fadeIn();
            that.promptingConent = "系统错误,请稍后再试!";
            that.promptingStatus = false;
            that.loadShow = false;
            that.dialog = that
              .$createDialog({
                type: "alert",
                title: "系统错误,请稍后再试!",
                content: "点击返回首页",
                icon: "cubeic-wrong",
                onConfirm: (e, promptValue) => {
                  that.$router.push({ path: "/main" });
                },
              })
              .show();
            setTimeout(function () {
              $("#fade").fadeOut();
            }, 2000);
          }
        });
      event.preventDefault();
    },
    validateHandler(result) {
      // this.submitHandler()
      console.log(result);
      this.resule = result;
      var that = this;

      that.validity = result.validity;
      that.valid = result.valid;
      // if (that.vali == true) {
      //   $("#fade").fadeIn();
      //   that.promptingConent = "提交失败,请填写必填信息!";
      //   that.promptingStatus = false;
      //   setTimeout(function() {
      //     $("#fade").fadeOut();
      //   }, 2000);
      // }
      // that.vali = false;
    },

    dateSelectHandler(selectedVal) {
      this.model.dateValue = new Date(
        selectedVal[0],
        selectedVal[1] - 1,
        selectedVal[2]
      ).toDateString();
    },
    filesAdded(files) {
      let hasIgnore = false;
      const maxSize = 1000 * 1024 * 1024; // 1M
      for (let k in files) {
        const file = files[k];
        if (file.size > maxSize) {
          file.ignore = true;
          hasIgnore = true;
        }
      }
      hasIgnore &&
        this.$createToast({
          type: "warn",
          time: 1000,
          txt: "不能上传超过100M的文件",
        }).show();
    },
    filesAdded1(files) {
      let hasIgnore = false;
      const maxSize = 1000 * 1024 * 1024; // 1M
      for (let k in files) {
        const file = files[k];
        if (file.size > maxSize) {
          file.ignore = true;
          hasIgnore = true;
        }
      }
      hasIgnore &&
        this.$createToast({
          type: "warn",
          time: 1000,
          txt: "不能上传超过100M的文件",
        }).show();
    },
    fileSubmitted(files) {
      this.action.data = { fileName: files.name };
    },
    fileSubmitted1(files) {
      this.action1.data = { fileName: files.name };
    },
    // 展示事件分类选择器
    showCategoryPicker() {
      this.categoryPicker.show();
    },
    // 选择事件分类
    selectCategoryHandler(selectedVal, selectedIndex, selectedTxt) {
      var selected = [];
      selectedTxt.forEach(function (v, i) {
        if (v != "") {
          selected.push(v);
        }
      });
      this.selectedCategoryTxt =
        this.model.title =
        this.model.description =
        this.incidentTitle =
          selected[selected.length - 1];
      this.model.category = selectedVal;
      this.selectedIndexCate = selectedIndex;
      // ----------------------回显其他数据---------------------
      console.log(selectedVal, "seimin");
      let reverseArr = selectedVal.filter(Boolean).reverse(); //数组翻转，取第一项不为空的
      let sjId = reverseArr[0]; //事件Id baba
      let sj = this.initSjList.filter((v) => v.id == sjId)[0];
      console.log(sj);
      this.model.priority = sj.priority.id;
      if (sj.userOrGroupType === 1) {
        //派人
        this.order = 2;
        this.model.handleUserOrGroup = true;
        this.model.handlerUser = sj.handleUser.id;
      } else if (sj.userOrGroupType === 2) {
        //派组
        this.order = 2;
        this.model.handleUserOrGroup = false;
        this.model.candidateGroups = sj.group.id;
      } else {
        this.order = 1;
        this.model.handleUserOrGroup = false;
        this.model.handlerUser = "";
        this.model.candidateGroups = "";
      }
    },
    // 事件分类
    getIncidentcategory() {
      var that = this;
      this.$http
        .post("/service/bpm/data/fetchDataList/incidentcategory", {
          idx: 0,
          sum: 1000,
        })
        .then(function (res) {
          that.initSjList = JSON.parse(JSON.stringify(res.data.list));
          var list = res.data.list;
          var tree = [];
          list.forEach((v, i) => {
            if (!v.parent) {
              tree[i] = {
                value: v.id,
                text: v.category,
                children: [],
              };
            } else {
              tree.forEach((val, idx) => {
                if (
                  v.parent &&
                  !v.parent.parent &&
                  val.text == v.parent.category
                ) {
                  tree[idx].children.push({
                    value: v.id,
                    text: v.category,
                    children: [],
                  });
                } else if (v.parent.parent) {
                  tree[idx].children.forEach((value, index) => {
                    if (value.text == v.parent.category) {
                      tree[idx].children[index].children.push({
                        value: v.id,
                        text: v.category,
                      });
                    }
                  });
                }
              });
            }
          });
          var idCate = [0, 0, 0];
          that.selectData = tree; //dada
          //报修转事件,回显一级分类
          var inspecInfo1 = that.$route.params.data;
          if (inspecInfo1 && inspecInfo1.category) {
            that.selectData.forEach(function (v, i) {
              if (v.value == inspecInfo1.category.id) {
                idCate = [v.value, 0, 0];
                that.selectedIndexCate = [i, 0, 0];
                that.selectedCategoryTxt = v.text;
              }
            });
            var sj = that.initSjList.find(function (v) {
              return v.id == inspecInfo1.category.id;
            });
            console.log(sj);
            if (sj.userOrGroupType === 1) {
              //派人
              that.order = 2;
              that.model.handleUserOrGroup = true;
              that.model.handlerUser = sj.handleUser.id;
            } else if (sj.userOrGroupType === 2) {
              //派组
              that.order = 2;
              that.model.handleUserOrGroup = false;
              that.model.candidateGroups = sj.group.id;
            } else {
              that.order = 1;
              that.model.handleUserOrGroup = false;
              that.model.handlerUser = "";
              that.model.candidateGroups = "";
            }
          }
          that.categoryPicker = that.$createCascadePicker({
            title: "事件分类选择",
            data: that.selectData,
            selectedIndex: that.selectedIndexCate,
            onSelect: that.selectCategoryHandler,
          });
        });
    },
    // 区域地点
    showPlacePicker() {
      this.placePicker.show();
    },
    selectPlaceHandler(selectedVal, selectedIndex, selectedTxt) {
      console.log(this.placeSelectData);
      console.log(selectedVal, selectedIndex, selectedTxt);
      // this.inpLocalVal = this.model.address = selectedTxt; //seimin
      // console.log(this.allPlace, "allPlace");
      // this.allPlace.forEach(item => {
      //   if (item.id == selectedVal && item.place) {
      //     //如果存在地点
      //     this.selectHouseNumber = this.allPlace[selectedIndex];
      //   }
      // });
      // console.log(this.selectHouseNumber, 2222);
      this.model.placeValue = selectedVal;
      this.selectedPlaceTxt = selectedTxt.join(" ");
      this.selectedIndex = selectedIndex;
    },
    // 报修科室
    showDeptPicker() {
      this.deptPicker.show();
    },
    // 选中报修科室
    selectDeptHandler(selectedVal, selectedIndex, selectedTxt) {
      console.log(selectedVal, selectedIndex, selectedTxt);
      this.deptInpVal = selectedTxt;
      this.model.requester = this.deptRes[selectedIndex];
      console.log(this.deptRes[selectedIndex]);
      this.inpLocalVal = this.model.address = this.deptRes[selectedIndex].place
        .area
        ? this.deptRes[selectedIndex].place.area.area
          ? this.deptRes[selectedIndex].place.place
            ? this.deptRes[selectedIndex].place.area.area +
              this.deptRes[selectedIndex].place.place
            : this.deptRes[selectedIndex].place.area.area
          : this.deptRes[selectedIndex].place.area
        : this.deptRes[selectedIndex].place.place;
      if (this.deptRes[selectedIndex].phone) {
        this.model.contactsInformation = this.deptRes[selectedIndex].phone;
      }
    },
    // 取消选中报修科室
    cancelDeptHandler() {
      if (this.model.requester) {
        this.deptInpVal = this.model.requester.dept;
      } else if (!this.model.requester) {
        this.deptInpVal = "";
        this.model.requester = "";
      }
    },
    getAreaData() {
      var that = this;
      this.$http
        .post("/service/user/data/fetchDataList/area", {
          idx: 0,
          sum: 1000,
          area: {
            wechatArea: true,
          },
        })
        .then(function (res) {
          var data = res.data.list;
          for (var i = 0; i < data.length; i++) {
            that.placeSelectData.push({
              text: data[i].area,
              value: data[i].id,
              children: [],
            });
          }
        });
    },
    getPlaceData() {
      var that = this;
      this.$http
        .post("/service/user/data/fetchDataList/place", {
          idx: 0,
          sum: 1000,
          area: {
            wechatAreaId: "",
          },
        })
        .then(function (res) {
          var data = res.data.list;
          for (var i = 0; i < data.length; i++) {
            for (var j = 0; j < that.placeSelectData.length; j++) {
              if (data[i].area.id == that.placeSelectData[j].value) {
                that.placeSelectData[j].children.push({
                  text: data[i].place,
                  value: data[i].id,
                });
              }
            }
          }
          var areaIndex = 0;
          var placeIndex = 0;
          that.placeSelectData.forEach(function (v, i) {
            if (that.model.placeValue[0] == v.value) {
              areaIndex = i;
            }
          });
          that.placeSelectData[areaIndex].children.forEach(function (v, i) {
            if (that.model.placeValue[1] == v.value) {
              placeIndex = i;
            }
          });
          that.selectedIndex = [areaIndex, placeIndex];
          that.placePicker = that.$createCascadePicker({
            title: "区域地点选择",
            data: that.placeSelectData,
            selectedIndex: that.selectedIndex,
            onSelect: that.selectPlaceHandler,
          });
        });
    },
    // 故障地点
    getFaultLocation(type) {
      var that = this;
      this.$http
        .post("/service/apply/bpm/searchFaultLocation", {
          searchKey: this.inpLocalVal || "",
        })
        .then(function (res) {
          var data = res.data.result;
          that.allPlace = JSON.parse(JSON.stringify(res.data.result));
          if (type == 1) {
            that.faultLocationList.length = 0;
            that.$set(that.faultLocationList, true, []);
            that.faultLocationList;
          }
          for (var i = 0; i < data.length; i++) {
            that.faultLocationList.push({
              text: data[i].area
                ? data[i].area.area
                  ? data[i].place
                    ? data[i].area.area + data[i].place
                    : data[i].area.area
                  : data[i].area
                : data[i].place,
              value: data[i].id,
            });
          }
          console.log(that.faultLocationList);

          that.placePicker = that.$createCascadePicker({
            title: "区域地点选择",
            data: that.faultLocationList,
            onSelect: that.selectPlaceHandler,
          });
          // that.fields[19].props.options = that.faultLocationList;
        });
    },
    // 故障地点输入框节流阀
    changeLocalList() {
      var that = this;
      this.model.address = this.inpLocalVal;
      console.log(this.inpLocalVal);
      clearTimeout(that.timer);
      that.timer = setTimeout(() => {
        this.getFaultLocation(1);
      }, 600);
    },
    // 报修科室
    getDept(type) {
      var that = this;
      this.$http
        .post("/service/user/data/fetchDataList/department", {
          idx: 0,
          sum: 50,
          department: { dept: that.deptInpVal || "" },
        })
        .then(function (res) {
          var data = res.data.list;
          if (type == 1) {
            that.deptList.length = 0;
            that.$set(that.deptList, true, []);
            that.deptList;
          }
          that.deptRes = res.data.list;
          for (var i = 0; i < data.length; i++) {
            that.deptList.push({
              text: data[i].dept,
              value: data[i].id,
            });
          }

          that.deptPicker = that.$createCascadePicker({
            title: "报修科室选择",
            data: that.deptList,
            onSelect: that.selectDeptHandler,
            onCancel: that.cancelDeptHandler,
          });
        });
    },
    changeDeptList() {
      var that = this;
      clearTimeout(that.timer);
      that.timer = setTimeout(() => {
        this.getDept(1);
      }, 600);
    },
  },
  created() {
    console.log(this.$route.params.data);
    //获取事件来源
    this.getSource();
    // 优先级
    this.getPriority();
    // 紧急度
    this.getMergency();
    // 影响度
    this.getInfluence();
    // 处理方式
    this.getHandleCategory();
    // 关闭代码
    this.getClosecode();
    // 处理人
    this.getHandlerUser();
    // 处理组
    this.getCandidateGroups();
    // this.getbxcode();
    this.getMessage();
    // 事件单号
    this.getsjnum();
    // 事件分类
    this.getIncidentcategory();
    this.getAreaData();
    this.getPlaceData();
    // 获取故障地点
    // this.getFaultLocation();
    if (this.valConfig == 2) {
      this.getDept();
    }
  },
  beforeRouteLeave(to, from, next) {
    console.log(to);
    if (to.name == "InspectionDetail") {
      this.$router.push({ name: "Inspection" });
    } else {
      next();
    }
  },
  mounted() {
    this.$refs.upload.pause();
    if (this.$refs.upload1) {
      this.$refs.upload1.pause();
    }
  },
  components: {
    CubePage,
    CubeButtonGroup,
    DatePicker,
    // JsonView
    CubeExtendPopup,
    LoadIng,
    PrompTing,
  },
};
</script>
<style>
.newIncident .cube-form-group {
  border-bottom: 0.02rem solid rgb(245, 245, 245);
}
.newIncident .sub .cube-btn {
  margin-top: 1.1rem;
}
.btn_plcaeholde .cube-btn {
  padding-left: 0;
  padding-right: 0;
  text-align: left;
  color: inherit;
  background: none;
  border: none;
}

.btn_local {
  /* z-index: 101; */
}
.inp_local {
  outline: none;
  width: 100%;
  height: 36px;
  color: #666;
}

.btn_plcaeholde .cube-btn::after {
  content: ">";
  float: right;
  margin-right: 0.15rem;
}
.cube-form_standard .cube-upload-def .cube-upload-btn,
.cube-form_standard .cube-upload-def .cube-upload-file {
  margin-left: 3% !important;
}
.sub .cube-btn {
  background-color: #005395 !important;
  width: 90%;
  margin: 0 auto;
  border-radius: 8px;
}
.cube-picker-wheel-item {
  text-overflow: ellipsis;
}
</style>
<style lang="less" scoped>
.zc{
  display:flex;
  position:relative;
  .zc-item{
    flex:7;
  }
  .zc-sao{
    flex:3;
    display:flex;
    justify-content:center;
    align-items:center;
    font-size:0.6rem;
  }
}
.header {
  width: 100%;
  height: 0.88rem;
  line-height: 0.88rem;
  text-align: center;
  color: #fff;
  font-size: 0.37rem;
  background: linear-gradient(#2e2f32, #414246);
  position: fixed;
  top: 0;
  z-index: 6;
}
.incidentTitle {
  .titleRefer {
    display: flex;
    align-items: center;
    justify-content: space-between;
    .titleTxtArea {
      font-size: 0.3rem;
      color: #333;
      height: auto;
      width: 62%;
      &:focus {
        outline: none;
      }
    }
    .abtn {
      display: inline-block;
      width: 37%;
      text-align: center;
      height: 0.48rem;
      color: #005395;
      font-size: 0.28rem;
    }
  }
}
.form-custom {
  .cube-form-item {
    .cube-btn {
      padding-left: 0;
      padding-right: 0;
      text-align: left;
      color: inherit;
      background: none;
      border: none;
    }
  }
}

.label {
  background-color: rgb(238, 238, 238);
  height: 0.6rem;
  line-height: 0.6rem;
  padding-left: 0.2rem;
  font-size: 0.24rem;
  color: #666666;
  span {
    font-size: 0.2rem;
    display: inline-block;
    margin-left: 0.08rem;
    color: #999999;
  }
  &.formLabel {
    background-color: #fff;
  }
}

.zhidu {
  display: flex;
  height: 0.7rem;
  line-height: 0.7rem;
  border-bottom: 0.02rem solid rgb(245, 245, 245);
  div:nth-child(1) {
    width: 27.5%;
    padding-left: 6%;
  }
}

.bgColor {
  background-color: white;
  &.newIncident {
    padding-top: 1.84rem;
  }
}

.uplod {
  padding: 0 0.24rem;
  border-bottom: 0.02rem solid rgb(245, 245, 245);
}
.navBar {
  width: 100%;
  height: 0.96rem;
  line-height: 0.96rem;
  background-color: #e5e5e5;
  font-size: 0.28rem;
  position: fixed;
  top: 0.88rem;
  z-index: 6;
  div {
    width: 49%;
    text-align: center;
    a {
      display: inline-block;
      height: 0.9rem;
      width: 1.7rem;
      padding: 0 0.3rem;
      &.active {
        color: #005395;
        border-bottom: 0.06rem solid #005395;
      }
    }
  }
}
.handleRadio {
  border-bottom: 0.02rem solid rgb(245, 245, 245);
}
</style>
