// 上报动态
import Utils from "../../../../utils/util"
const app = getApp();

Page({

  /**
   * 页面的初始数据
   */
  data: {
    topBarH: app.globalData.CustomBar,
    baseUrl: app.FILE_SERVER_URL,

    dateFilter: Utils.formatTime(new Date(), '-'),
    showTypePop: false,
    showAdvicePop: false,
    TypeData: [],
    postData: {},
    files: [],
    userInfo:{},

    areamultiArray:[],
  areamultiIndex: [0, 0, 0],
  areamultiIds: [],
  areanewArr: [],
  area:[],
  areatate : false,

  multiArray: [],
  multiIndex: [0, 0, 0],
    multiIds: [],
    newArr: [],
    organization:[],
    organizationtate : false,
  },

  /**
   * 显示/关闭弹窗
   */
  popModal: function (params) {
    const type = params.currentTarget.dataset.type;
    this.data[type] = !this.data[type];
    this.setData(this.data)
  },

  /**
   * 事件类型
   */
  typeChange: function (params) {
    const index = params.currentTarget.dataset.index;
    console.log(params,'params===>');
    this.data.postData.emerTypeId = params.currentTarget.dataset.item.emerTypeId;
    this.data.postData.type = index + 1;
    this.data.showTypePop = false;
    this.setData(this.data);
  },

  /**
   * 输入框赋值
   */
  inputContent: function (e) {
    const name = e.currentTarget.dataset.name;
    this.data.postData[name] = e.detail.value;
    this.setData(this.data);
  },

  /**
   * 发布
   */
  push: function () {
    if (!this.data.postData.title) {
      wx.showToast({
        title: '请输入标题',
        icon: 'none'
      })
      return
    }
    if (!this.data.postData.createTime) {
      wx.showToast({
        title: '请选择时间',
        icon: 'none'
      })
      return
    }
    if (!this.data.postData.emerTypeId) {
      wx.showToast({
        title: '请选择事件类型',
        icon: 'none'
      })
      return
    }
     
    if (this.data.organizationtate==false) {
      wx.showToast({
        title: '请选择所属组织',
        icon: 'none'
      })
      return
    }
    if (this.data.areatate==false) {
      wx.showToast({
        title: '请选择地区',
        icon: 'none'
      })
      return
    }
    if (!this.data.postData.addressName) {
      wx.showToast({
        title: '请选择详细地址',
        icon: 'none'
      })
      return
    }
    if (!this.data.postData.content) {
      wx.showToast({
        title: '请输入事件描述',
        icon: 'none'
      })
      return
    }
    
    let data = {
      ...this.data.postData,
      emerEventId:this.data.uuid,
      userId:this.data.userInfo.userId,
      address:this.data.postData.addressName,
    };
    data.listPerformId = this.data.organization?this.data.multiArray[0].children[0].children[this.data.organization[2]].listperformid:'';
    data.areaCode = this.data.areamultiArray[0].children[this.data.area[1]].orgcode?this.data.areamultiArray[0].children[this.data.area[1]].orgcode:'';
    console.log(data,'data===>');
    app.axios("POST", "app", `/emerEvent/saveEmerEvent`,data).then(res => {
      console.log(res,'res===>');
      if (res.code == 1) {
        wx.showToast({
          title: '发布成功',
          icon: 'none'
        })
        setTimeout(() => {
          wx.navigateBack()
        }, 1500);
      } else {
        wx.showToast({
          title: res.message,
          icon: 'none'
        })
      }
    })
  },
  getweidu:function (params) {
    wx.getLocation({
      type: 'gcj02', //返回可以用于wx.openLocation的经纬度
      success (res) {
        const latitude = res.latitude
        const longitude = res.longitude
        wx.openLocation({
          latitude,
          longitude,
          scale: 18
        })
      }
     })
  },

  /**
   * 选择文件
   */
  chooseFile: function () {
    wx.chooseImage({
      count: 1,
      type: 'all',
      success: (res) => {
        const tempFilePaths = res.tempFiles;
        const path = tempFilePaths[0].path;
        this.postImg(path)
      }
    })
  },

  /**
   * 上传图片
   */
  postImg(filePath) {
    wx.showLoading({
      title: '文件上传中...',
    })
    app.uploadFile(this.data.uuid, app.FileType.eventAcs, filePath).then(res => {
    
      let resdata = JSON.parse(res);
      console.log(resdata,'resdata===>');
      // if (resdata.code == 1) {
        console.log(resdata,'res==>');
        wx.hideLoading();
          this.getFiles();
      // }
    })
  },

  /**
   * 获取图片
   */
  getFiles: function () {
    console.log(1111);
    app.axios("GET", "common", "/upload/getFile", {
      otcid: this.data.postData.emerEventId || this.data.uuid,
      otctype: app.FileType.eventAcs
    }).then(res => {
      if (res.code == 1) {
        console.log(res,'res===>');
        this.data.files = res.data;
        this.setData(this.data)
      }
    })
  },

  /**
   * 删除图片
   * @param {*} params 
   */
  deleteFile: function (e) {
    var id = e.currentTarget.dataset.id;
    wx.showModal({
      title: '删除提示',
      content: '是否要删除该附件？',
      success: (res) => {
        if (res.confirm) {
          app.axios("GET", 'common', "/upload/delFile", {
            documentId: id,
          }).then(res => {
            if (res.code == 1) {
              this.getFiles();
            }
          })
        }
      }
    })
  },

  /**
   * 预览文件
   */
  filePre: function (params) {
    const url = params.currentTarget.dataset.url;
    const imgs = [];
    this.data.files.forEach(item => {
      imgs.push(this.data.baseUrl + item.filepath)
    })
    wx.previewImage({
      urls: imgs,
      current: this.data.baseUrl + url
    })
  },

  /**
   * 时间
   */
  bindDateChange: function (params) {
    this.data.postData.createTime = params.detail.value;
    this.setData(this.data)
  },

  /**
   * 选择位置
   */
  // chooseAddress: function (params) {
  //   wx.chooseLocation({
  //     success: (res) => {
  //       this.data.postData.lat = res.latitude;
  //       this.data.postData.lng = res.longitude;
  //       this.data.postData.address = res.address;
  //       this.setData(this.data)
  //     }
  //   })
  // },
   /**
   * 查询所有应急上报事件类型
   */
  getEmerEventType: function () {
    app.axios("GET", "app", "/emerEvent/emerEventType").then(res => {
      if (res.code == 1) {
        console.log(res);
        this.data.TypeData = res.data;
        this.setData(this.data);
      }
    })
  },

/**
   * 查看应急上报事件详情
   */
  getEmerEventDetail: function (id) {
    app.axios("GET", "app", `/emerEvent/emerEventDetail/${id}`).then(res => {
      if (res.code == 1) {
        this.data.postData = res.data;
        this.data.postData.emerTypeName;
        for (let index = 0; index < this.data.TypeData.length; index++) {
          if (this.data.TypeData[index].emerTypeName == res.data.emerTypeName) {
            this.data.postData.type = index+1;
          }
        };
        this.setData(this.data);
        this.getFiles();
      }
    })
  },
// 地区获取
getAreaTree: function () {
  app.axios("GET", "common", "/sysorg/areaTree").then(res => {
    if (res.code == 1) {
      console.log(res);
      this.data.areamultiArray = res.data;
      this.data.areamultiArray[0].children.forEach(item => {
        item.children = []
      });
      this.setData(this.data);
      let state = {
        arr: [],
        arr1: [],
        arr2: [],
        arr3: [],
        areamultiIds: []
      }
      this.data.areamultiArray.map((v, vk) => {
        state.arr1.push(v.orgname);
        if (this.data.areamultiIndex[0] === vk) {
          state.areamultiIds[0] = v;
        }
        if (state.arr2.length <= 0) {
          v.children.map((c, ck) => {
            state.arr2.push(c.orgname);
            if (this.data.areamultiIndex[1] === ck) {
              state.areamultiIds[1] = c;
            }
            if (state.arr3.length <= 0) {
              c.children.map((t, tk) => {
                state.arr3.push(t.orgname);
                if (this.data.areamultiIndex[2] === tk) {
                  state.areamultiIds[2] = t;
                }
              });
            }
          });
        }
      });
      state.arr[0] = state.arr1;
      state.arr[1] = state.arr2;
      state.arr[2] = state.arr3;
      this.setData({
        areanewArr: state.arr,
        areamultiIds: state.areamultiIds,
      });
    }
  })
},
  // 级联选择地区
  areabindMultiPickerChange(e) {
    console.log(this.data.areamultiIds,'级联选择地区==>');
    this.setData({
      area: e.detail.value,
      areatate:true
    });
  },
  areabindMultiPickerColumnChange(e) {
    let data = {
      areanewArr: this.data.areanewArr,
      areamultiIndex: this.data.areamultiIndex,
      areamultiIds: this.data.areamultiIds,
    };
    data.areamultiIndex[e.detail.column] = e.detail.value;

    let searchColumn = () => {
      let arr1 = [];
      let arr2 = [];
      this.data.areamultiArray.map((v, vk) => {
        if (data.areamultiIndex[0] === vk) {
          data.areamultiIds[0] = {
            ...v,
          };
          v.children.map((c, ck) => {
            arr1.push(c.orgname);
            if (data.areamultiIndex[1] === ck) {
              data.areamultiIds[1] = {
                ...c,
              };
              c.children.map((t, vt) => {
                arr2.push(t.orgname);
                if (data.areamultiIndex[2] === vt) {
                  data.areamultiIds[2] = {
                    ...t,
                  };
                }
              });
            }
          });
        }
      });
      data.areanewArr[1] = arr1;
      data.areanewArr[2] = arr2;
    };
    switch (e.detail.column) {
      case 0:
        // 每次切换还原初始值
        data.areamultiIndex[1] = 0;
        data.areamultiIndex[2] = 0;
        // 执行函数处理
        searchColumn();
        break;
      case 1:
        data.areamultiIndex[2] = 0;
        searchColumn();
        break;
    }
    this.setData(data);
  },

  
// 所属组织获取
getAreaTree1: function () {
  app.axios("GET", "app", "/Sys/getListperformTree").then(res => {
    if (res.code == 1) {
      console.log(res);
      this.data.multiArray = res.data
      this.setData(this.data);
      
    let state = {
      arr: [],
      arr1: [],
      arr2: [],
      arr3: [],
      multiIds: []
    }
    this.data.multiArray.map((v, vk) => {
      state.arr1.push(v.performclassname);
      if (this.data.multiIndex[0] === vk) {
        state.multiIds[0] = v;
      }
      if (state.arr2.length <= 0) {
        v.children.map((c, ck) => {
          state.arr2.push(c.performclassname);
          if (this.data.multiIndex[1] === ck) {
            state.multiIds[1] = c;
          }
          if (state.arr3.length <= 0) {
            c.children.map((t, tk) => {
              state.arr3.push(t.performclassname);
              if (this.data.multiIndex[2] === tk) {
                state.multiIds[2] = t;
              }
            });
          }
        });
      }
    });
    state.arr[0] = state.arr1;
    state.arr[1] = state.arr2;
    state.arr[2] = state.arr3;
    this.setData({
      newArr: state.arr,
      multiIds: state.multiIds,
    });
    }
  })
},
bindMultiPickerChange(e) {
  console.log(e,'e==>');

  this.setData({
    organization: e.detail.value,
    organizationtate:true
  });
  console.log(this.data.organization,'e==>');
  console.log(this.data.multiIds);
},
bindMultiPickerColumnChange(e) {
  let data = {
    newArr: this.data.newArr,
    multiIndex: this.data.multiIndex,
    multiIds: this.data.multiIds,
  };
  data.multiIndex[e.detail.column] = e.detail.value;

  let searchColumn = () => {
    let arr1 = [];
    let arr2 = [];
    this.data.multiArray.map((v, vk) => {
      if (data.multiIndex[0] === vk) {
        data.multiIds[0] = {
          ...v,
        };
        v.children.map((c, ck) => {
          arr1.push(c.performclassname);
          if (data.multiIndex[1] === ck) {
            data.multiIds[1] = {
              ...c,
            };
            c.children.map((t, vt) => {
              arr2.push(t.performclassname);
              if (data.multiIndex[2] === vt) {
                data.multiIds[2] = {
                  ...t,
                };
              }
            });
          }
        });
      }
    });
    data.newArr[1] = arr1;
    data.newArr[2] = arr2;
  };
  switch (e.detail.column) {
    case 0:
      // 每次切换还原初始值
      data.multiIndex[1] = 0;
      data.multiIndex[2] = 0;
      // 执行函数处理
      searchColumn();
      break;
    case 1:
      data.multiIndex[2] = 0;
      searchColumn();
      break;
  }
  this.setData(data);
},

//地点选择/经纬度
toShowAddress() {
  let that = this;
  wx.chooseLocation({
    success(res) {
      that.data.postData.lat = res.latitude;
      that.data.postData.lon = res.longitude;
      that.data.postData.addressName = res.name;
      that.setData(that.data);
    },
  })
},





  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.data.uuid = Utils.uuid();
    this.data.userInfo = app.globalData.userInfo;
    this.setData(this.data);
    this.getEmerEventType();
    this.getAreaTree();
    this.getAreaTree1();
    if (options.emerEventId) {
      console.log(options.emerEventId,'options.emerEventId===>');
      this.getEmerEventDetail(options.emerEventId)
    }
  },



  

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})