// packageE/form/form.js
var app = getApp();
Component({
  properties: {
    datas: {
      type: null,
    },
    component_id: {
      type: null,
    },
  },
  // 私有数据，可用于模板渲染
  data: {
    emptyImage: "https://mini-app-img-1251768088.cos.ap-guangzhou.myqcloud.com/image.png",
    clientWidth: "375",

    status: 0, // 是否已提交
    startDate: new Date("1900-01-01"),
    Height: "",
    formList: [],
    showAddress: false,
    form_id: "",
    shoTime: "",
    types: {
      88: "diyusername",
      99: "diypassword",
      0: "diyinput",
      1: "diytextarea",
      3: "diycheckbox",
      4: "diyradio",
      2: "diyselect",
      7: "diydate",
      9: "diycity",
      5: "diyimage",
    },
    diydata: [],
    setname: "",
    uploadUrl: "upload.uploadPic",
    //地区
    provinceData: [],
    cityData: [],
    districtData: [],
    pickerValue: [0, 0, 0],
    selectAddressData: [],
    currentDate: new Date().getTime(),
    showCity1: false,
  },

  lifetimes: {
    // 生命周期函数，可以为函数，或一个在methods段中定义的方法名
    attached() {
      console.log(this.properties.datas);
    },
    moved() {},
    detached() {},
  },

  // 生命周期函数，可以为函数，或一个在methods段中定义的方法名
  attached() {},
  // 此处attached的声明会被lifetimes字段中的声明覆盖
  ready() {
    this.setData({
      clientWidth: wx.getSystemInfoSync().windowWidth,
    });

    this._initAddressInfo();
    if (this.data.datas.form.title) {
      this.getForm(this.data.datas.list);
    }
  },

  pageLifetimes: {
    // 组件所在页面的生命周期函数
    show() {},
    hide() {},
    resize() {},
  },
  methods: {
    //获取表单信息
    getForm(data) {
      let that = this;

      this.setData({
        form_id: this.data.datas.list.id,
      });

      if (data) {
        that.setData({
          status: data.status,
          loading: true,
        });
        if (that.data.status === 1) {
          that.setData({
            diyform: data,
          });
          const fields = that.data.diyform.fields;
          for (let field in fields) {
            var list = {
              title: fields[field].tp_name,
              value: fields[field].value,
              data_type: fields[field].data_type,
              tp_must: fields[field].tp_must,
            };
            if (list.data_type == "3") {
              list.value = fields[field].value.join(",");
            }
            if (list.data_type == "7") {
              list.value = fields[field].default_time;
            }
            if (list.data_type == "1") {
              list.value = fields[field].value;
            }
            that.data.formList.push(list);
            that.setData({
              formList: that.data.formList,
            });
          }
        } else {
          that.setData({
            diyform: data,
          });
          let fields = that.data.diyform.fields;
          let diydata = that.data.diydata;
          let f = null;
          for (var field in fields) {
            if (that.data.types[fields[field].data_type] == "diycheckbox") {
              f = {
                name: field,
                data: fields[field],
                value: [],
                type: that.data.types[fields[field].data_type],
              };
            }
            // else if (that.data.types[fields[field].data_type] == "diydate") {
            //   f = {
            //     name: field,
            //     data: fields[field],
            //     value: "",
            //     type: that.data.types[fields[field].data_type],
            //   };
            // }
            else if (that.data.types[fields[field].data_type] == "diyselect") {
              let tp_textArr = [];
              for (let i = 0; i < fields[field].tp_text.length; i++) {
                tp_textArr.push({
                  name: fields[field].tp_text[i],
                });
              }
              f = {
                name: field,
                data: fields[field],
                value: "",
                type: that.data.types[fields[field].data_type],
                diysishow: false,
                sitem: tp_textArr,
              };
            } else if (that.data.types[fields[field].data_type] == "diycity") {
              f = {
                name: field,
                data: fields[field],
                value: "",
                type: that.data.types[fields[field].data_type],
                showAdd: false,
              };
            } else if (that.data.types[fields[field].data_type] == "diydate") {
              f = {
                name: field,
                data: fields[field],
                value: "",
                type: that.data.types[fields[field].data_type],
                timeShow: false,
                currentDate: new Date().getTime(),
              };
            } else if (that.data.types[fields[field].data_type] == "diyimage") {
              f = {
                name: field,
                data: fields[field],
                imgUrls: [],
                isPhoto: false,
                type: that.data.types[fields[field].data_type],
              };
            } else {
              f = {
                name: field,
                data: fields[field],
                value: "",
                type: that.data.types[fields[field].data_type],
              };
            }
            diydata.push(f);
            that.setData({
              diydata: diydata,
            });
          }
        }
      }
    },
    getFormBack() {
      let that = this;
      let urlStr = app.getNetAddresss(
        "plugin.diyform.api.diy-form.getDiyFormTypeMemberData"
      );
      urlStr +=
        "&form_id=" + this.data.datas.form_id
          ? this.data.datas.form_id
          : this.data.datas.form.id;
      app._getNetWork({
        url: urlStr,
        success: function (resdata) {
          var res = resdata.data;
          if (res.result == 1) {
            that.setData({
              status: res.data.status,
              loading: true,
            });
            if (that.data.status === 1) {
              that.setData({
                diyform: res.data,
                thumb: res.data.thumb,
              });
              const fields = that.data.diyform.fields;
              for (let field in fields) {
                var list = {
                  title: fields[field].tp_name,
                  value: fields[field].value,
                  data_type: fields[field].data_type,
                  tp_must: fields[field].tp_must,
                };
                if (list.data_type == "3") {
                  list.value = fields[field].value.join(",");
                }
                if (list.data_type == "7") {
                  list.value = fields[field].default_time;
                }
                if (list.data_type == "1") {
                  list.value = fields[field].value;
                }
                that.data.formList.push(list);
                that.setData({
                  formList: that.data.formList,
                });
              }
            } else {
              that.setData({
                diyform: res.data,
              });
              let fields = that.data.diyform.fields;
              let diydata = that.data.diydata;
              let f = null;
              for (var field in fields) {
                if (that.data.types[fields[field].data_type] == "diycheckbox") {
                  f = {
                    name: field,
                    data: fields[field],
                    value: [],
                    type: that.data.types[fields[field].data_type],
                  };
                }
                // else if (
                //   that.data.types[fields[field].data_type] == "diydate"
                // ) {
                //   f = {
                //     name: field,
                //     data: fields[field],
                //     value: "",
                //     type: that.data.types[fields[field].data_type],
                //   };
                // }
                else if (
                  that.data.types[fields[field].data_type] == "diyselect"
                ) {
                  let tp_textArr = [];
                  for (let i = 0; i < fields[field].tp_text.length; i++) {
                    tp_textArr.push({
                      name: fields[field].tp_text[i],
                    });
                  }
                  f = {
                    name: field,
                    data: fields[field],
                    value: "",
                    type: that.data.types[fields[field].data_type],
                    diysishow: false,
                    sitem: tp_textArr,
                  };
                } else if (
                  that.data.types[fields[field].data_type] == "diycity"
                ) {
                  f = {
                    name: field,
                    data: fields[field],
                    value: "",
                    type: that.data.types[fields[field].data_type],
                    showAdd: false,
                  };
                } else if (
                  that.data.types[fields[field].data_type] == "diydate"
                ) {
                  f = {
                    name: field,
                    data: fields[field],
                    value: "",
                    type: that.data.types[fields[field].data_type],
                    timeShow: false,
                    currentDate: new Date().getTime(),
                  };
                } else if (
                  that.data.types[fields[field].data_type] == "diyimage"
                ) {
                  f = {
                    name: field,
                    data: fields[field],
                    imgUrls: [],
                    isPhoto: false,
                    type: that.data.types[fields[field].data_type],
                  };
                } else {
                  f = {
                    name: field,
                    data: fields[field],
                    value: "",
                    type: that.data.types[fields[field].data_type],
                  };
                }
                diydata.push(f);
                that.setData({
                  diydata: diydata,
                });
              }
            }
          }
        },
        fail: function (res) {
          console.log(res);
        },
      });
    },
    //自定义表单值绑定
    tpnameinp(e) {
      let val = e.detail.value;
      let idx = e.currentTarget.dataset.idex;

      this.setData({
        ["diydata[" + idx + "].value"]: val,
      });
    },
    onRead_1(e) {
      let name = e.currentTarget.dataset.name;
      this.setData({
        setname: name,
      });
      let that = this;
      let urlStr = app.getNetAddresss(this.data.uploadUrl);
      wx.chooseImage({
        count: 1,
        sizeType: ["original", "compressed"],
        sourceType: ["album", "camera"],
        success(res) {
          const tempFilePaths = res.tempFilePaths;
          wx.compressImage({
            src: tempFilePaths[0], // 图片路径
            quality: 60, // 压缩质量
            success(e) {
              let photourl = e.tempFilePath;

              wx.uploadFile({
                url: urlStr,
                filePath: photourl,
                name: "file",
                formData: {
                  attach: that.data.setname,
                },
                success(resdata) {
                  var res = JSON.parse(resdata.data);
                  if (res.result == 1) {
                    let diydata = that.data.diydata;
                    for (var i = 0; i < diydata.length; i++) {
                      if (diydata[i].name == res.data.attach) {
                        diydata[i].imgUrls.push(res.data.img_url);
                      }
                    }
                    that.setData({
                      diydata: diydata,
                    });
                  } else {
                    wx.showToast({
                      icon: "none",
                      title: res.msg,
                      duration: 1500,
                    });
                  }
                },
              });
            },
            fail(e) {
              console.log(e);
            },
            complete(e) {},
          });
        },
      });
    },
    removeImg: function (e) {
      let delIndex = e.currentTarget.dataset.indexc;
      let index_1 = e.currentTarget.dataset.index;
      let diydata = this.data.diydata;
      diydata[index_1].imgUrls.splice(delIndex, 1);
      this.setData({
        diydata: diydata,
      });
    },
    diytextareainp(e) {
      let val = e.detail;
      let idx = e.currentTarget.dataset.idex;
      this.setData({
        ["diydata[" + idx + "].value.value"]: val,
      });
    },
    checkboxinp(e) {
      let val = e.detail;
      let idx = e.currentTarget.dataset.idex;
      this.setData({
        ["diydata[" + idx + "].value"]: val,
      });
    },
    diyselectBtn(e) {
      let idx = e.currentTarget.dataset.idex;
      this.setData({
        ["diydata[" + idx + "].diysishow"]: true,
      });
    },
    raidinp(e) {
      let val = e.detail;
      let idx = e.currentTarget.dataset.idex;
      this.setData({
        ["diydata[" + idx + "].value"]: val,
      });
    },
    //所在地选择显示
    showAddBtn(e) {
      let idx = e.currentTarget.dataset.idex;
      this.setData({
        ["diydata[" + idx + "].showAdd"]: true,
      });
    },
    // 关闭选择收货地址
    _closeDateLw: function (e) {
      let idx = e.currentTarget.dataset.idex;
      this.setData({
        ["diydata[" + idx + "].showAdd"]: false,
      });
    },
    //地址选择器数据初始化
    _initAddressInfo: function () {
      var that = this;
      var _keyName = "provinceData";
      wx.getStorage({
        key: _keyName,
        success: function (res) {
          that._getProvinceData();
        },
        fail: function (res) {
          app._getNetWork({
            url: app.getNetAddresss("member.member-address.address"),
            success: function (res) {
              var response = res.data;
              var province = response.data.province;
              var city = response.data.city;
              var district = response.data.district;
              wx.setStorage({
                key: "provinceData",
                data: province,
              });
              wx.setStorage({
                key: "cityData",
                data: city,
              });
              wx.setStorage({
                key: "districtData",
                data: district,
              });
              that._initAddressInfo();
            },
            fail: function (res) {},
            state: true,
          });
        },
      });
    },
    // 读取省key
    _getProvinceData: function () {
      var that = this;
      var _keyName = "provinceData";
      wx.getStorage({
        key: _keyName,
        success: function (res) {
          that.setData({
            provinceData: res.data,
          });
          that.setData({
            "selectAddressData[0].name":
              res.data[that.data.pickerValue[0]].areaname,
            "selectAddressData[0].id": res.data[that.data.pickerValue[0]].id,
            "selectAddressData[0].index": that.data.pickerValue[0],
          });
          that._getCityData();
        },
      });
    },
    // 读取城市key，筛选城市data
    _getCityData: function () {
      var _data = this.data.selectAddressData[0];
      var that = this;
      var _keyName = "cityData";
      wx.getStorage({
        key: _keyName,
        success: function (res) {
          var _json = [];
          for (var i = 0; i < res.data.length; i++) {
            if (res.data[i].parentid == _data.id) {
              _json.push(res.data[i]);
            }
          }
          that.setData({
            cityData: _json,
          });
          that.setData({
            "selectAddressData[1].name":
              _json[that.data.pickerValue[1]].areaname,
            "selectAddressData[1].id": _json[that.data.pickerValue[1]].id,
            "selectAddressData[1].index": that.data.pickerValue[1],
          });
          that._getDistrictData();
        },
      });
    },
    // 读取地区key，筛选地区data
    _getDistrictData: function () {
      var _data = this.data.selectAddressData[1];
      var that = this;
      var _keyName = "districtData";
      wx.getStorage({
        key: _keyName,
        success: function (res) {
          var _json = [];
          for (var i = 0; i < res.data.length; i++) {
            if (res.data[i].parentid == _data.id) {
              _json.push(res.data[i]);
            }
          }
          that.setData({
            districtData: _json,
          });
          that.setData({
            "selectAddressData[2].name":
              _json[that.data.pickerValue[2]].areaname,
            "selectAddressData[2].id": _json[that.data.pickerValue[2]].id,
            "selectAddressData[2].index": that.data.pickerValue[2],
          });
        },
      });
    },
    // 收货地址滚动事件
    bindChange: function (e) {
      var val = e.detail.value;
      if (this.data.pickerValue[0] != val[0]) {
        val[1] = 0;
        val[2] = 0;
      }
      if (this.data.pickerValue[1] != val[1]) {
        val[2] = 0;
      }
      this.setData({
        "pickerValue[0]": val[0],
        "pickerValue[1]": val[1],
        "pickerValue[2]": val[2],
      });
      this._initAddressInfo();
    },
    //城市结果
    resultAdd: function (e) {
      let idx = e.currentTarget.dataset.idex;
      let seleData = this.data.selectAddressData;
      let retCity =
        seleData[0].name + " " + seleData[1].name + " " + seleData[2].name;
      this.setData({
        ["diydata[" + idx + "].value"]: retCity,
        ["diydata[" + idx + "].showAdd"]: false,
      });
    },
    //自定义日期选择
    openPicker(e) {
      let idx = e.currentTarget.dataset.idex;
      this.setData({
        ["diydata[" + idx + "].timeShow"]: true,
      });
    },
    _closeDateLw_1() {
      this.setData({
        showCity1: false,
      });
    },
    resultAdd_1() {
      let seleData = this.data.selectAddressData;
      this.setData({
        "applyModel.province_name": seleData[0].name,
        "applyModel.city_name": seleData[1].name,
        "applyModel.district_name": seleData[2].name,
        fullAddress:
          seleData[0].name + " " + seleData[1].name + " " + seleData[2].name,
        showCity1: false,
      });
    },
    submit() {
      this.validation();
      if (!this.data.isValidation) {
        return;
      }
      this.submitForm();
    },
    validation() {
      this.setData({
        isValidation: true,
      });
      this.data.diydata.forEach((item) => {
        if (item.data.tp_must == 1 && !item.value && item.type != "diyimage") {
          wx.showToast({
            icon: "none",
            title: item.data.tp_name + "必须填写哦",
            duration: 1500,
          });
          this.setData({
            isValidation: false,
          });
        }
        if (item.data.tp_must == 1 && item.type == "diyimage") {
          if (item.imgUrls.length < item.data.tp_max) {
            wx.showToast({
              icon: "none",
              title: item.data.tp_name + "必须上传" + item.data.tp_max + "张",
              duration: 1500,
            });
            this.setData({
              isValidation: false,
            });
          }
        }
        if (item.type == "diycheckbox" && item.value.length == 0) {
          wx.showToast({
            icon: "none",
            title: item.data.tp_name + "必须选择哦",
            duration: 1500,
          });
          this.setData({
            isValidation: false,
          });
        }
      });
    },
    //自定义表单提交
    submitForm() {
      var that = this;
      var formData = [];
      var formObject = {};
      this.data.diydata.forEach((item) => {
        //图片类型的直接提交图片base64的数组到后台，其它直接传值
        if (item.type == "diyimage") {
          formObject[item.name] = item.imgUrls;
        } else {
          formObject[item.name] = item.value;
        }
      });
      formData.push(formObject);
      let json = {
        form_id: this.data.datas.form_id
          ? this.data.datas.form_id
          : this.data.datas.form.id,
        form_data: formData,
      };
      let urlStr = app.getNetAddresss(
        "plugin.diyform.api.diy-form.save-form-data"
      );
      app._postNetWork({
        url: urlStr,
        showToastIn: false,
        data: json,
        success: function (resdata) {
          var res = resdata.data;
          if (res.result == 1) {
            wx.showToast({
              icon: "success",
              title: "提交成功",
              duration: 1500,
            });
            that.getFormBack();
          } else {
            wx.showToast({
              icon: "none",
              title: res.msg,
              duration: 1500,
            });
          }
        },
        fail: function (res) {},
      });
    },
    showCity1btn() {
      this.setData({
        showCity1: true,
      });
    },
    sitemSelectBtn(e) {
      let val = e.detail.name;
      let idx = e.currentTarget.dataset.index;
      this.setData({
        ["diydata[" + idx + "].value"]: val,
        ["diydata[" + idx + "].diysishow"]: false,
      });
    },
    sitemClose(e) {
      let idx = e.currentTarget.dataset.index;
      this.setData({
        ["diydata[" + idx + "].diysishow"]: false,
      });
    },
    dateClose(e) {
      let index = e.currentTarget.dataset.idex;
      this.setData({
        ["diydata[" + index + "].timeShow"]: false,
      });
    },
    //日期转化
    timestampToTime(timestamp) {
      var date = new Date(timestamp);
      let Y = date.getFullYear() + "-";
      let M =
        (date.getMonth() + 1 < 10
          ? "0" + (date.getMonth() + 1)
          : date.getMonth() + 1) + "-";
      let D = this.change(date.getDate()) + " ";
      return Y + M + D;
    },
    change(t) {
      if (t < 10) {
        return "0" + t;
      } else {
        return t;
      }
    },
    birthdayconfirm(e, time) {
      let index = e.currentTarget.dataset.idex;
      let val = e.detail;
      this.setData({
        ["diydata[" + index + "].value"]: String(val).substring(0, 10),
        shoTime: this.timestampToTime(val),
        ["diydata[" + index + "].timeShow"]: false,
      });
    },
  },
});
