<template>
  <div>
    <el-form :rules="rules" :model="formData" ref="children">
      <el-form-item label="子女个数" prop="childrenNum" ref="childrenNum">
        <el-select v-model="formData.childrenNum" placeholder="请选择" @change="selectNum">
          <el-option
            v-for="item in options"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          ></el-option>
        </el-select>
      </el-form-item>
    </el-form>
    <el-form
      :key="index"
      v-for="(value,index) in formDatas"
      :rules="rules"
      ref="childrenData"
      :model="value"
      class="login_form"
    >
      <p>子女信息{{index+1}}</p>
      <el-form-item prop="name" label="子女姓名" ref="name">
        <el-input
          v-model="value.name"
          autocomplete="off"
          placeholder="请填写姓名"
          style="width: 220px"
          @blur="(val)=>{addChildren(val,index,'name')}"
        ></el-input>
      </el-form-item>
      <el-form-item label="子女性别" ref="sex" prop="sex">
        <el-radio-group
                v-model="value.sex"
                style="width: 220px"
                @change="(val)=>{addChildren(val,index,'sex')}"
        >
          <el-radio label="男"></el-radio>
          <el-radio label="女"></el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item prop="phone" label="子女联系电话" ref="phone">
        <el-input
          v-model="value.phone"
          autocomplete="off"
          placeholder="请填写常用联系电话或手机号"
          style="width: 220px"
          @blur="(val)=>{addChildren(val,index,'phone')}"
        ></el-input>
      </el-form-item>
      <el-form-item prop="isHasGoOut" label="是否外出" ref="isHasGoOut">
        <el-select v-model="value.isHasGoOut" placeholder="请选择" @change="selectGoOut(index)">
          <el-option
                  v-for="item in goOut"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
          ></el-option>
        </el-select>
      </el-form-item>
      <div class="partner" v-if="value.isHasGoOut == '是'">
      <el-form-item prop="outgoingCause" label="外出原因" ref="outgoingCause">
        <el-input
          v-model="value.outgoingCause"
          autocomplete="off"
          placeholder="请填写外出原因"
          style="width: 220px"
          @blur="(val)=>{addChildren(val,index,'outgoingCause')}"
        ></el-input>
      </el-form-item>
      <div :id="'trigger4'" v-show="false" style="width: 0;height: 0"></div>
      <el-form-item prop="outgoingplace" label="外出地点" ref="outgoingplace">
        <el-col
          :span="24"
          @click.native="changdept(index)"
          :style="`color:${value.outgoingplace === ''||value.outgoingplace ==='请选择' ? '#409EFF':''}`"
        >{{value.outgoingplace || '点击选择外出地点'}}</el-col>
      </el-form-item>
        <el-form-item label="最后一次离家时间" prop="outgoingTime" ref="outgoingTime">
          <el-col
                  class="ss"
                  :span="24"
                  @click.native="clickDate(index)"
                  :style="`color:${value.outgoingTime === ''||value.outgoingTime ==='请选择' ? '#409EFF':''}`"
          >{{ value.outgoingTime || '点击选择最后一次离家时间'}}</el-col>
          <!-- <mt-datetime-picker
                          class="opt_picker"
                          v-model.trim="date"
                          type="date"
                          ref="picker"
                          @confirm="changeDateValue()"
                          year-format="{value} 年"
                          month-format="{value} 月"
                  >
          </mt-datetime-picker>-->
        </el-form-item>
      </div>
      <el-form-item prop="isHasPartner" label="是否有配偶" ref="isHasPartner">
        <el-select v-model="value.isHasPartner" placeholder="请选择" @change="selectSpouse(index)">
          <el-option
            v-for="item in spouses"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          ></el-option>
        </el-select>
      </el-form-item>
      <div class="partner" v-if="value.isHasPartner == '是'">
        <el-form-item prop="name2" label="子女配偶姓名" ref="name2">
          <el-input
            v-model="value.name2"
            autocomplete="off"
            placeholder="请填写子女配偶姓名"
            style="width: 220px"
            @blur="(val)=>{addChildren(val,index,'name2')}"
          ></el-input>
        </el-form-item>
        <el-form-item prop="phone2" label="子女配偶电话" ref="phone2">
          <el-input
            v-model="value.phone2"
            autocomplete="off"
            placeholder="请填写常用联系电话"
            style="width: 220px"
            @blur="(val)=>{addChildren(val,index,'phone2')}"
          ></el-input>
        </el-form-item>
      </div>
      <div :id="'trigger5'" v-show="false" style="width: 0;height: 0"></div>

      <el-form-item prop="visit" label="平均一年探望次数" ref="visit">
        <el-select
          v-model="value.visit"
          placeholder="请填写平均一年探望次数"
          @change="(val)=>{addChildren(val,index,'visit')}"
        >
          <el-option
            v-for="item in childrenTimes"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          ></el-option>
        </el-select>
      </el-form-item>
      <hr style="width: 220px" />
    </el-form>
    <el-image
      :src="require('../../assets/ic_tip.png')"
      style="position: fixed;top:10vh;right: 10px;width: 20px;"
      @click="toScroll()"
    />
  </div>
</template>

<script>
import PickerExtend from "picker-extend";
import date from "../../util/date";
import areaList from "../../util/area";
import areaListList from "../../util/area1";
import { updateOlds } from "../../api";

export default {
  name: "children3",
  props: ["id", "clickTabIndex", "childrenData"],
  data() {
    let checkName = (rule, value, callback) => {
      if (!value) {
        callback(new Error("姓名不能为空"));
      } else {
        let reg = /^(?:[\u4e00-\u9fa5·]{2,16})$/;
        if (!reg.test(value)) {
          callback(new Error("请输入中文格式"));
        } else {
          callback();
        }
      }
    };
    let checkName1 = (rule, value, callback) => {
      if (!value) {
        callback(new Error("子女配偶姓名不能为空"));
      } else {
        let reg = /^[\u2E80-\u9FFF]+$/;
        if (!reg.test(value)) {
          callback(new Error("请输入中文格式"));
        } else {
          callback();
        }
      }
    };
    return {
      isColor: "",
      areaListList: areaListList,
      mobileSelect4: "",
      mobileSelect5: "",
      show: false,
      isShow: false,
      isSpouses: false,
      clickCount: 1,
      formData: {
        childrenNum: ""
      },
      formDatas: [],
      index: "",
      oldId: "",
      deptIndex: "",
      areaList: areaList,
      //date: new Date(),
      date: date.date,
      options: [
        { value: "0", label: "0个" },
        { value: "1", label: "1个" },
        { value: "2", label: "2个" },
        { value: "3", label: "3个" },
        { value: "4", label: "3个以上" }
      ],
      spouses: [
        { value: "是", label: "是" },
        { value: "否", label: "否" }
      ],
      goOut: [
        { value: "是", label: "是" },
        { value: "否", label: "否" }
      ],
      childrenTimes: [
        { value: "0", label: "0次" },
        { value: "1", label: "1次" },
        { value: "2", label: "2次及以上" }
      ],
      childrenList: {},
      rules: {
        //数据校验规则
        name: [{ required: true, validator: checkName, trigger: "blur" }],
        sex: [{required: true, message: "性别不能为空", trigger: "change"}],
        name2: [{ required: true, validator: checkName1, trigger: "blur" }],
        phone: [{ required: true, message: "手机号不能为空", trigger: "blur" }],
        phone2: [
          { required: true, message: "手机号不能为空", trigger: "blur" }
        ],
        childrenNum: [
          { required: true, message: "请选择子女个数", trigger: "blur" }
        ],
        outgoingplace: [
          { required: true, message: "请选择外出地点", trigger: "blur" }
        ],
        isHasPartner: [
          { required: true, message: "请选择是否有配偶", trigger: "blur" }
        ],
        isHasGoOut: [
          { required: true, message: "请选择是否外出", trigger: "blur" }
        ],
        outgoingTime: [
          { required: true, message: "请选择最后一次离家时间", trigger: "blur" }
        ],
        visit: [
          { required: true, message: "请选择平均一年探望次数", trigger: "blur" }
        ],
        outgoingCause: [
          { required: true, message: "请填写外出原因", trigger: "blur" }
        ]
      }
    };
  },
  methods: {
    changdept(index) {
      this.clickCount = index;
      this.mobileSelect4.show();
    },
    clickPlace(index) {
      this.deptIndex = index;
      this.mobileSelect4.show();
    },
    clickDate(index) {
      console.log("dsdsdsds");
      this.clickCount = index;
      this.mobileSelect5.show();
      // this.deptIndex = index;
      // this.$refs.picker[index].open()
    },
    toScroll() {
      setTimeout(() => {
        let vKey = "";
        this.$refs["childrenData"].forEach((value, index) => {
          value.validate((valid, obj) => {
            if (!valid) {
              if (!vKey) {
                Object.keys(obj).forEach(item => {
                  if (!vKey) {
                    vKey = item;
                  }
                });
                this.$refs[vKey][index].$el.scrollIntoView({
                  behavior: "auto",
                  block: "center",
                  inline: "nearest"
                });
              }
            }
          });
        });
      }, 200);
    },

    /*  Scroll() {
                  setTimeout(()=> {
                      this.$refs['loginForm'].validate((valid) => {
                          if (valid) {
                              this.isColor = true;
                              this.$emit("patrolisColor", this.isColor, this.index);

                          } else {
                              this.isColor = false;
                              this.$emit("patrolisColor", this.isColor, this.index);

                          }
                      });
                      this.$refs['loginForm'].clearValidate();
                  },200);

              },*/

    Scroll(isSelect) {
      setTimeout(() => {
        if (this.formDatas.length > 0) {
          // 填写了 123
          let isComplete = false;
          this.$refs["childrenData"].forEach(item => {
            console.log(item, "sss");
            item.validate(valid => {
              if (!isComplete) {
                if (valid) {
                  console.log("chengs");
                  this.isColor = true;
                  this.$emit("childrenisColor", this.isColor, this.index);
                } else {
                  console.log("unchengs");
                  this.isColor = false;
                  this.$emit("childrenisColor", this.isColor, this.index);
                  isComplete = true;
                }
              }
            });
            item.clearValidate();
          });
          /*   this.$refs['childrenData'].validate((valid) => {
                               if (valid) {
                                   this.isColor = true;
                                   this.$emit("childrenisColor", this.isColor, this.index);
                               } else {
                                   this.isColor = false;
                                   this.$emit("childrenisColor", this.isColor, this.index);

                               }
                           });
                           this.$refs['loginForm'].clearValidate();*/
        } else {
          // 填写了0个
          if (this.childrenList.childInfo) {
            this.isColor = true;
            this.$emit("childrenisColor", this.isColor, this.index);
          } else {
            //我啥都没填
            if (isSelect) {
              this.isColor = true;
              this.$emit("childrenisColor", this.isColor, this.index);
            } else {
              this.isColor = false;
              this.$emit("childrenisColor", this.isColor, this.index);
            }
          }
        }
      }, 200);
    },
    forCount(index) {
      if (index > 3) {
        index = 3;
      }
      this.formDatas = [];
      for (let i = 0; i < index; i++) {
        this.formDatas.push({
          name: "",
          phone: "",
          sex: "",
          isHasPartner: "",
          isHasGoOut:"是",
          outgoingplace: "",
          outgoingCause:'',
          name2: "",
          phone2: "",
          outgoingTime: "",
          visit: ""
        });
      }
      console.log(this.formDatas,"我是所有的字段");
    },
    selectNum(value) {
      this.forCount(value);
      this.Scroll(true);
      this.updateOlds();
      this.updateNum(value);
    },
    selectSpouse(index) {
      this.formDatas[index].name2 = "";
      this.formDatas[index].phone2 = "";
      this.selectChildrenInfo();
    },
    selectGoOut(index) {
      this.formDatas[index].outgoingCause = "";
      this.formDatas[index].outgoingplace = "";
      this.formDatas[index].outgoingTime="";
      this.selectChildrenInfo();
    },

    isDateString(str) {
      return /\d{4}(-|\/|.)\d{1,2}\1\d{1,2}/.test(str);
    },
    getYear(value) {
      return this.isDateString(value)
        ? value.split(" ")[0].split(/-|\/|\./)[0]
        : value.getFullYear();
    },

    getMonth(value) {
      return this.isDateString(value)
        ? value.split(" ")[0].split(/-|\/|\./)[1]
        : value.getMonth() + 1;
    },

    getDate(value) {
      return this.isDateString(value)
        ? value.split(" ")[0].split(/-|\/|\./)[2]
        : value.getDate();
    },

    changeDateValue() {
      let year = this.getYear(this.date);
      let month = this.getMonth(this.date);
      this.formDatas[this.deptIndex].outgoingTime = year + "-" + month;

      this.selectChildrenInfo();
    },
    selectChildrenInfo() {
      console.log("chankana");
      this.Scroll();
      this.updateOlds();
    },
    addChildren(v1, index, v2) {
      console.log(index);
      this.$refs["childrenData"][index].validateField(v2, emailError => {
        if (!emailError) {
          this.Scroll();
          this.updateOlds();
        } else {
          //this.Scroll();
          this.$emit("childrenisColor", false, this.index);
          this.updateOlds();
          return false;
        }
      });
    },
    async updateNum(value) {
      await updateOlds({ id: this.oldId, childrenNum: value });
    },
    async updateOlds() {
      let result = await updateOlds({
        id: this.oldId,
        childInfo: JSON.stringify(this.formDatas)
      });
      if (result.code === 0) {
        console.log(result);
      }
    },
    cascading() {
      this.areaListList.dept.forEach((pro, pi) => {
        pro.id = pi + "";
        pro.childs.forEach((city, ci) => {
          city.id = pi + "" + ci;
          city.childs = city.area.map((area, ai) => {
            let obj = {};
            obj.id = pi + "" + ci + ai;
            obj.name = area;
            return obj;
          });
        });
      });
      let that = this;
      this.mobileSelect4 = new PickerExtend({
        trigger: "#trigger4",
        title: "选择地区",
        wheels: [{ data: this.areaListList.dept }],
        keyMap: {
          id: "id",
          value: "name",
          childs: "childs"
        },
        position: [0, 0], //初始化定位
        callback: function(indexArr, data) {
          let arr = [];
          data.forEach(item => {
            arr.push(item.name);
          });
          //记录 点击的索引
          let clickCount = that.clickCount;
          that.formDatas[clickCount].outgoingplace = arr.join("/");
          that.Scroll();
          that.updateOlds({
            id: that.oldId,
            outgoingplace: that.formDatas[clickCount].outgoingplace
          });
        }
      });
    },
    cascading1() {
      let that = this;
      this.mobileSelect5 = new PickerExtend({
        trigger: "#trigger5",
        title: "选择最后一次离家时间",
        wheels: [{ data: this.date }],
        position: [0, 0], //初始化定位
        callback: function(indexArr, data) {
          //记录 点击的索引
          let clickCount = that.clickCount;
          if (data.length === 1) {
            that.formDatas[clickCount].outgoingTime = data[0].value;
          } else {
            that.formDatas[clickCount].outgoingTime =
              data[0].value.slice(0, 4) + "-" + data[1].value.slice(0, 2);
          }
          //that.formDatas[clickCount].outgoingplace = arr.join("/");
          that.Scroll();
          that.updateOlds({
            id: that.oldId,
            outgoingTime: that.formDatas[clickCount].outgoingTime
          });
        }
      });
    },
    removeExcess(data) {
      if (data) {
        data = JSON.parse(data);
      }
      return data;
    },
    getList() {
      if (this.childrenData) {
        this.childrenList = this.childrenData;
        this.oldId = this.childrenList._id;
        if (this.childrenList.childInfo) {
          const result = this.removeExcess(this.childrenList.childInfo);
          this.formDatas = result.map(item=>{
            console.log("item",item);
            if(!item.isHasGoOut) {
              if(item.outgoingplace||item.outgoingCause||item.outgoingTime) {
                return Object.assign(item,{isHasGoOut: "是"})
              }else
              {
                return Object.assign(item,{isHasGoOut: "否"})
              }
            }
            return item
          });
          console.log(this.formDatas,"1111");
          result.forEach(value => {
            console.log("我是回显的数",value);
            if (value.isHasPartner === "是") {
              this.isSpouses = true;
              this.isHasPartner = "是";
            } else {
              this.isSpouses = false;
              this.isHasPartner = "否";
            }
            //外出
            if(value.isHasGoOut==="是"){
              this.isHasGoOut="是";
            }else{
              this.isHasGoOut="否"
            }
            //
          });
          if (this.childrenList.childrenNum == 4) {
            this.formData.childrenNum = "4";
          } else {
            this.formData.childrenNum = this.formDatas.length + "";
          }
        } else {
          // this.formData.childrenNum = "0";
        }
        this.Scroll();
      }
    }
  },
  watch: {
    id(newValue) {
      this.oldId = newValue;
    },
    clickTabIndex(newValue) {
      this.index = newValue;
    },
    childrenData(newValue) {
      this.childrenList = newValue;
    }
  },
  mounted() {
    this.oldId = this.id;
    this.index = this.clickTabIndex;
    this.getList();
    this.cascading();
    this.cascading1();
  }
};
</script>

<style scoped>
.opt_picker >>> .picker-slot-center:nth-child(3) {
  display: none;
}
.ss {
  text-align: left;
}
.partner {
  padding: 10px;
  border: 1px solid #eee;
  background-color: #f1f1f1;
}
</style>
