<template>
  <div class="diy_form">
    <div v-for="(item,h) in diydata" :key="h">
      <el-form-item v-if="item.type == 'diyinput'" :label="item.data.tp_name">
        <el-input :placeholder="item.data.placeholder || '请填写'" v-model="item.value">
        </el-input>
      </el-form-item>
      <el-form-item v-if="item.type == 'diytextarea'" :label="item.data.tp_name">
        <el-input type="textarea" maxlength="100" :placeholder="item.data.placeholder" v-model="item.value">
        </el-input>
      </el-form-item>
      <el-form-item v-if="item.type == 'diycheckbox'" :label="item.data.tp_name">
        <div v-for="(ck,i) in item.data.tp_text" :key='i'>
          <el-checkbox-group v-model="item.value">
            <el-checkbox :label="ck">{{ck}}</el-checkbox>
          </el-checkbox-group>
        </div>
      </el-form-item>
      <el-form-item v-if="item.type == 'diypwd'" :label="item.data.tp_name===''?'密码':`${item.data.tp_name}`">
        <el-input :placeholder="item.data.placeholder" v-model="item.value">
        </el-input>
      </el-form-item>
      <el-form-item v-if="item.type == 'diyusername'" :label="item.data.tp_name===''?'账号':`${item.data.tp_name}`">
        <el-input :placeholder="item.data.placeholder" v-model="item.value">
        </el-input>
      </el-form-item>
      <el-form-item v-if="item.type == 'diyselect'" :label="item.data.tp_name">
        <el-select v-model="item.value" placeholder="请选择">
          <el-option v-for="(sitem,i) in item.data.tp_text" :key="i" :label="sitem" :value="sitem">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item v-if="item.type == 'diyradio'" :label="item.data.tp_name">
        <el-radio-group v-model="item.value">
          <el-radio :label="ritem" v-for="(ritem,i) in item.data.tp_text" :key="i">{{ ritem }}</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item v-if="item.type == 'diydate'" :label="item.data.tp_name">
        <el-date-picker v-model="item.value" type="date" placeholder="请选择日期" value-format="yyyy-MM-dd">
        </el-date-picker>
      </el-form-item>
      <el-form-item v-if="item.type == 'diycity'" :label="item.data.tp_name">
        <el-cascader :options="district" v-model="item.value" :props="diyform_props"></el-cascader>
      </el-form-item>
      <el-form-item v-if="item.type == 'diyimg'" :label="item.data.tp_name">
        <div class="flex" style="flex-wrap:wrap;width:360px;">
          <div style="margin-right:20px;margin-bottom:20px;position:relative;" class="avatar"
               v-for="(val, index) in item[item.name + 'Value2']" :key="index">
            <img src="~/assets/images/icon/delete.png" style="position:absolute;right:-10px;top:-10px;cursor:pointer;"
                 @click="removeImg_1(item, index)"/>
            <img :src="val.url" style="width:100%;height:100%;">
          </div>
          <div @click="chooseUpload(item.name)">
            <el-upload :disabled="item[item.name + 'Length'].length >= item.data.tp_max" class="avatar-uploader"
                       :on-success="diySuccess" :action="uploadUrl" :show-file-list="false">
              <i class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
          </div>
        </div>
      </el-form-item>
    </div>
  </div>
</template>

<script>
  import District from "~/static/js/gov_province_city_area_id";

  export default {
    name: 'formDiy',
    props: {
      diydata: Array
    },
    data() {
      return {
        uploadUrl: '',
        district: [],
        diyform_props: {
          value: "n",
          children: "c",
          label: "n"
        },
      };
    },
    mounted() {
      if(!window.localStorage.getItem('provinceData')) {
        this._initAddressInfo();
      }else {
        this.district = JSON.parse(window.localStorage.getItem('provinceData'));
      }
      this.uploadUrl = this.fun.getRealUrl("upload.uploadPic", {});
    },
    methods: {
      _initAddressInfo() {
        this.fun.$get("member.member-address.address", {}, "正在获取").then(res => {
          if (res.result == 1) {
            let provinces = [];
            let citys = [];

            res.data.province.map((province) => {
              provinces.push({
                "v": province.id,
                "n": province.areaname,
                "c": []
              })
            });
            res.data.city.map((city) => {
              citys.push({
                "parentid": city.parentid,
                "v": city.id,
                "n": city.areaname,
                "c": []
              })
            });
            res.data.district.map((district) => {
              citys.map((city) => {
                if (district.parentid == city.v) {
                  city.c.push({
                    "v": district.id,
                    "n": district.areaname
                  })
                }
              });
            });

            citys.map((city) => {
              provinces.map((province) => {
                if (city.parentid == province.v) {
                  province.c.push({
                    "v": city.v,
                    "n": city.n,
                    "c": city.c
                  })
                }
              })
            });

            provinces.map((province) => {
              if (province.c.length == 0) {
                province.c = ""
              } else {
                province.c.map((c) => {
                  if (c.c.length == 0) {
                    c.c = ""
                  }
                })
              }
            });

            this.district = provinces;
            if(provinces) {
              window.localStorage.setItem('provinceData',JSON.stringify(provinces));
            }
          }
        });
      },
      removeImg_1(item, delIndex) {
        console.log(item);
        var index = 0;
        var real_name = "";
        for (let i = 0; i < this.diydata.length; i++) {
          if (item.name == this.diydata[i].name) {
            real_name = this.diydata[i].name;
            console.log(real_name);
            index = i;
            break;
          }
        }
        this.diydata[index][real_name + "Value1"].splice(delIndex, 1);
        this.diydata[index][real_name + "Value2"].splice(delIndex, 1);
        this.diydata[index][real_name + "Length"] = this.diydata[index][
        real_name + "Value1"
          ].length;
      },
      chooseUpload(name) {
        this.upload_name = name;
        console.log(this.upload_name);
        return true;
      },
      diySuccess(res, file) {
        var That = this;
        var real_length = 0;
        var max_length = 0;
        var real_list1 = [];
        var real_list2 = [];
        var index = 0;
        var real_name = "";

        for (let i = 0; i < this.diydata.length; i++) {
          if (this.upload_name == this.diydata[i].name) {
            real_name = this.diydata[i].name;
            console.log(real_name);
            index = i;

            max_length = this.diydata[i].data.tp_max;
            real_list1 = this.diydata[i][real_name + "Value1"];
            real_list2 = this.diydata[i][real_name + "Value2"];
            console.log(this.diydata[i][real_name + "Value1"]);
            break;
          }
        }
        if (
          this.diydata[index][real_name + "Length"] ==
          this.diydata[index].data.tp_max ||
          this.diydata[index][real_name + "Length"] >=
          this.diydata[index].data.tp_max
        ) {
          console.log(this.diydata[index].data.tp_max);
          this.$message.error("图片数量已达到上限");
          return false;
        }
        this.diydata[index][real_name + "Length"]++;
        this.diydata[index][real_name + "Value1"].push({
          url: res.data.img
        });
        this.diydata[index][real_name + "Value2"].push({
          url: res.data.img_url
        });
      },
      postDiy(member_id) {
        var that = this;
        var formData = [];
        var formObject = {};
        this.diydata.forEach(item => {
          if (item.type == "diycity") {
            if (item.value.length && item.value.length > 0) {
              item.value = item.value.join(",");
            }
          }
          if (item.type == "diyimg") {
            var arr = [];
            for (let i = 0; i < item[item.name + "Value1"].length; i++) {
              arr.push(item[item.name + "Value1"][i].url);
            }
            formObject[item.name] = arr;
          } else {
            formObject[item.name] = item.value;
          }
        });
        formData.push(formObject);
        console.log(formData);
        console.log("i miss");

        let json = {
          form_data: formData,
          form_id: this.form_id,
          member_id: member_id,//商城注册页面时需要的参数
          form_type: "register"//商城注册页面时需要的参数
        };
        console.log(json);

        this.fun
          .$post(
            "plugin.diyform.api.diy-form.save-diy-form-data",
            json,
            "提交中..."
          )
          .then(response => {
            if (response.result == 1) {
              that.$message.success(response.msg);
              that.$emit('diySuccess', true)
            } else {
              that.$message.error(response.msg);
            }
          });
      },
      //验证参数
      validation() {
        let isValidation = true;
        let flag = true;
        this.diydata.some(item => {
          if (item.data.tp_must == 1 && !item.value && item.type != "diyimg") {
            console.log(item.data.tp_name, item.value);
            isValidation = false;
            this.$emit('pausepost', isValidation)
            this.$message.error(item.data.tp_name + "必须填写哦");
            return true;
          }
          if (item.data.tp_must == 1 && item.type == "diyimg") {
            if (item[item.name + "Length"] <= 0) {
              isValidation = false;
              this.$emit('pausepost', isValidation)
              this.$message.error(item.data.tp_name + "必须填写哦");
              return true;
            }
          }
          if (item.type == "diycheckbox" && item.value.length == 0) {

            isValidation = false;
            this.$emit('pausepost', isValidation)
            this.$message.error(item.data.tp_name + "必须填写哦");
            return true;
          } else {
            this.$emit('pausepost', true)
          }
        });

      },
    }
  };
</script>
<style lang="scss" scoped>

</style>
