<template>
  <div v-loading="loading">
    <el-form ref="ruleForm" :model="ruleForm" :rules="rules" label-width="150px" class="order_form">
      <!-- <el-form-item label="会员卡编号" prop="vipcode">
        <el-input v-model="ruleForm.F_VIPCode" placeholder="请输入会员卡编号"></el-input>
      </el-form-item> -->
      <el-form-item label="客户姓名" prop="F_Name">
        <el-input v-model="ruleForm.F_Name" placeholder="请输入客户姓名"></el-input>
      </el-form-item>
      <el-form-item label="客户性别" prop="F_Sex">
        <el-radio v-model="ruleForm.F_Sex" label="男">男</el-radio>
        <el-radio v-model="ruleForm.F_Sex" label="女">女</el-radio>
      </el-form-item>
      <el-form-item label="客户年龄" prop="F_Age">
        <el-input v-model="ruleForm.F_Age" placeholder="请输入客户年龄" onkeyup="value=value.replace(/[^\d.]/g,'')"></el-input>
      </el-form-item>
      <el-form-item label="手机号码1" prop="F_Mobile">
        <el-input v-model="ruleForm.F_Mobile" placeholder="请输入手机号码1"></el-input>
      </el-form-item>
      <el-form-item label="手机号码2" prop="F_Mobile1">
        <el-input v-model="ruleForm.F_Mobile1" placeholder="请输入手机号码2"></el-input>
      </el-form-item>
      <el-form-item label="联系方式" prop="F_Phone">
        <el-input v-model="ruleForm.F_Phone" placeholder="请输入联系方式"></el-input>
      </el-form-item>
      <el-form-item label="会员标签" prop="F_Type">
        <el-select v-model="ruleForm.F_Type" clearable placeholder="请选择会员标签" class="form_select">
          <el-option
            v-for="item in memberType"
            :key="item.F_ID"
            :label="item.F_Name"
            :value="item.F_Name">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="地区" prop="provinceCity">
         <el-cascader
        v-model="provinceCity"
        :options="provinceCityDatas"
        :props="props"
        :placeholder="placeholderArea"
        class="form_select"
        :class="{'placeholderAreaClass':isPlaceholderAreaClass} "
        @change="handleItemChange"
        ref="myCascader"
        clearable
        change-on-select/>
      </el-form-item>
      <el-form-item label="详细地址" prop="F_Address">
        <el-input v-model="ruleForm.F_Address" placeholder="请输入详细地址"></el-input>
      </el-form-item>
      <el-form-item label="备用地址" prop="F_Address1">
        <el-input v-model="ruleForm.F_Address1" placeholder="请输入备用地址"></el-input>
      </el-form-item>
      <el-form-item label="邮编" prop="F_Postcode">
        <el-input v-model="ruleForm.F_Postcode" placeholder="请输入邮编"></el-input>
      </el-form-item>
      <el-form-item label="鞋码" prop="F_ShoeSize">
        <el-input v-model="ruleForm.F_ShoeSize" placeholder="请输入鞋码" onkeyup="value=value.replace(/[^\d.]/g,'')"></el-input>
      </el-form-item>
      <el-form-item label="会员生日" prop="F_Birthday">
        <el-date-picker
        value-format="yyyy-MM-dd"
          v-model="ruleForm.F_Birthday"
          type="date"
          placeholder="请选择会员生日"
          class="form_date"
        ></el-date-picker>
      </el-form-item>
      <el-form-item label="会员积分" prop="F_Score">
        <el-input v-model="ruleForm.F_Score" placeholder="请输入会员积分" onkeyup="value=value.replace(/[^\d.]/g,'')"></el-input>
      </el-form-item>
      <el-form-item label="推荐人" prop="F_Recommender">
        <el-input v-model="ruleForm.F_Recommender" placeholder="请输入推荐人"></el-input>
      </el-form-item>
      <el-form-item label="累计消费金额" prop="F_Money">
        <el-input v-model="ruleForm.F_Money" placeholder="请输入累计消费金额" onkeyup="value=value.replace(/[^\d.]/g,'')"></el-input>
      </el-form-item>
      <el-form-item label="累计积分" prop="F_TotalScore">
        <el-input v-model="ruleForm.F_TotalScore" placeholder="请输入累计积分" onkeyup="value=value.replace(/[^\d.]/g,'')"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submitForm">保存</el-button>
        <el-button @click="resetForm">重置</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import { getProviceCityById } from "@/api/commonAPI";
import {
  getMemberInfo,
  addOrder,
  editOrder,
  getLabelLists
} from "@/api/memberManagement/memberList";
import { validateTel } from "@/utils/validate";
import { filterContent,pickerOptions } from "@/utils";

export default {
  name: "AddOrEdit",
  props: {
    rowid: {
      type: String,
      default: ""
    },
    callid: {
      type: Number,
      default: 0
    },
    layerid: {
      type: String,
      default: ""
    }
  },
  data() {
    return {
      sourceOptions: [], // 工单来源下拉数据
      memberType: [], // 会员类型下拉数据
      provinceCityDatas: [], // 省市下拉数据
      provinceCity: [], // 省市下拉绑定的值
      provinceCityText: [], // 省市下拉绑定的文本值
      props: {
        // 自定义省市下拉数据的key值
        value: "id",
        label: "text",
        children: "children"
      },
      addressParams: {
        pid: 1
      },
      isPlaceholderAreaClass:true,
      placeholderArea:'',//地区默认值
      level: 0, //城市等级
      pickerOptions ,// 日期数据
      ruleForm: {
        unique_id: "", //		否	string	callid
        id: "", //编辑会员信息id
        // F_VIPCode: "", //会员卡编号
        F_Name: "", //客户姓名
        F_Sex: "男", //客户性别
        F_Age: "", //客户年龄
        F_Mobile: "", //手机号码
        F_Mobile1: "", //手机号码1
        F_Phone: "", //固定电话
        F_Type: "", //会员类型
        // province: "", //省
        // city: "", //市
        // county: "", //县/区
        // township: "", //乡镇
        F_Address: "", //详细地址
        F_Address1: "", //备用地址
        F_Postcode: "", //邮编
        F_ShoeSize: "", //鞋码
        F_Birthday: "", //会员生日
        F_Score: "", //会员积分
        F_Recommender: "", //推荐人
        F_Money: "", //累计消费金额
        F_TotalScore: "" //累计积分
      },
      rules: {
        F_Name: [
          {
            required: true,
            trigger: "blur",
            message: "请输入客户姓名"
          }
        ],
        F_Phone: [
          {
            required: true,
            trigger: "blur",
            message: "请输入联系方式"
          }
        ]
      },
      loading: false
    };
  },
  created() {
    this.getProCity()
    if (this.callid) {
      this.ruleForm.unique_id = this.callid;
    }
    Promise.all([]).then(() => {
      this.getType();
      if (this.rowid) {
        this.ruleForm.id = this.rowid;
        this.getDetail(this.rowid);
      }else{
        this.placeholderArea='请选择地区';
        this.isPlaceholderAreaClass=false
      }
    });
  },
  methods: {
    submitForm() {
      this.$refs.ruleForm.validate(valid => {
        if (valid) {
          this.ruleForm.content = filterContent.delHtmlTag(
            this.ruleForm.content
          ); // 保存内容时去掉 html 标签
          this.loading = true;
          return new Promise(resolve => {
            const params = {
              id: this.rowid ? this.rowid : '',
              state:'1',
              name: this.ruleForm.F_Name, //客户姓名
              phone: this.ruleForm.F_Phone, //固定电话
              recommender: this.ruleForm.F_Recommender, //推荐人
              sex: this.ruleForm.F_Sex, //性别
              age: this.ruleForm.F_Age, //年龄
              label: this.ruleForm.F_Type, //会员类型
              mobile: this.ruleForm.F_Mobile, //手机号码
              mobile1: this.ruleForm.F_Mobile1, //手机号码1
              address: this.ruleForm.F_Address, //详细地址
              address1: this.ruleForm.F_Address1, //备用地址
              postcode: this.ruleForm.F_Postcode, //邮编
              province: this.provinceCityText && this.provinceCityText[0], //省份
              city: this.provinceCityText && this.provinceCityText[1], //市
              area: this.provinceCityText && this.provinceCityText[2], //县
              town: this.provinceCityText && this.provinceCityText[3], //乡
              province1: this.provinceCity && this.provinceCity[0], //省份
              city1: this.provinceCity && this.provinceCity[1], //市
              area1: this.provinceCity && this.provinceCity[2], //县
              town1: this.provinceCity && this.provinceCity[3], //乡
              shoesize: this.ruleForm.F_ShoeSize, //鞋码
              birthday: this.ruleForm.F_Birthday, //会员生日
              score: this.ruleForm.F_Score, //会员积分
              money: this.ruleForm.F_Money, //累计消费金额
              totalscore: this.ruleForm.F_TotalScore //累计积分
            };
            // 添加
          if (!this.rowid) {
            addOrder(params)
              .then(response => {
                this.loading = false;
                if (response.state.toLowerCase() === "success") {
                  this.$parent.$layer.close(this.layerid);
                  this.$parent.btn_search(); // 重新加载父级数据
                  this.$message.success("恭喜你，添加成功!");
                }
              })
              .catch(() => {
                this.loading = false;
              });
            return;
          }
          // 编辑
          editOrder(params)
            .then(response => {
              this.loading = false;
              if (response.state.toLowerCase() === "success") {
                this.$parent.$layer.close(this.layerid);
                this.$parent.getList(); // 重新加载父级数据
                this.$message.success("恭喜你，编辑成功!");
              }
            })
            .catch(() => {
              this.loading = false;
            });
          });
          
        } else {
          this.$message.error("请输入有效的必填项信息!");
          return false;
        }
      });
    },
    resetForm() {
      this.$refs.ruleForm.resetFields();
      this.provinceCityText = [];
      this.provinceCity = [];
      this.placeholderArea='请选择地区';
      this.isPlaceholderAreaClass=false
    },
    // 详情
    getDetail(rid) {
      getMemberInfo(rid).then(response => {
        if (response.state.toLowerCase() === "success") {
          this.ruleForm = response.data;
          this.ruleForm.F_Type = response.data.F_Label
          if(response.data.F_Province){
            if(response.data.F_City){
              this.placeholderArea = response.data.F_Province+'/'
            }else{
              this.placeholderArea = response.data.F_Province
            }
            if(response.data.F_City && response.data.F_Area){
              this.placeholderArea += response.data.F_City+'/'
            }else{
              this.placeholderArea += response.data.F_City
            }
            if(response.data.F_Area && response.data.F_Town){
              this.placeholderArea += response.data.F_Area+'/'
            }else{
              this.placeholderArea += response.data.F_Area
            }
            if(response.data.F_Town){
            this.placeholderArea += response.data.F_Town
            }
            this.provinceCityText=this.placeholderArea.split('/')
          }else{
            this.placeholderArea='请选择地区';
            this.isPlaceholderAreaClass=false
          }
          
        }
      });
    },
    // 获取会员类型
    getType() {
      return new Promise(resolve=>{
        const params={
          pageindex:1,
          pagesize:100,
        }
        getLabelLists(params).then(response => {
          if (response.state.toLowerCase() === 'success') {
            this.memberType= response.rows.Rows
          }
        })
      })
    },
    // 获取省市下拉数据
    getProCity() {
      getProviceCityById(this.addressParams)
        .then(res => {
          this.provinceCityDatas = this.handleData(res.data);
        })
        .catch(err => {});
    },
    handleItemChange(val) {
      this.provinceCityText=this.$refs['myCascader'].currentLabels
      let pid = val ? val[val.length - 1] : 1; //id值
      this.level = val.length + 1; //判断第几级
      this.provinceCityDatas = this.handleData(
        this.provinceCityDatas,
        pid,
        this.level
      );
    },
    handleData(data, val, level) {
      for (let i = 0; i < data.length; i++) {
        if (!data[i].children) {
          this.$set(data[i], "children", []);
        }
        if (data[i].id === val) {
          getProviceCityById({ pid: val })
            .then(res => {
              if (res.data.length) {
                data[i].children = res.data;
                if(this.level!==4){
                  data[i].children.forEach(ele => {
                    this.$set(ele, "children", []);
                  });
                }
              } else {
                data[i].children = undefined;
              }
            })
            .catch(err => {});
        } else {
          if (data[i].children.length) {
            this.handleData(data[i].children, val,level);
          }
        }
      }

      return data;
    },
  }
};
</script> 

<style rel="stylesheet/scss" lang="scss">
.order_form {
  .form_select {
    width: 100%;
  }
  .form_date {
    width: 100%;
  }
  .col_select_text {
    text-align: right;
    padding-right: 15px;
  }
}
.placeholderAreaClass .el-input__inner::-webkit-input-placeholder { /* WebKit browsers */
  color: #606266;
  font-size: 14px;
}

.placeholderAreaClass .el-input__inner::-moz-placeholder { /* Mozilla Firefox 19+ */
  color: #606266;
  font-size: 14px;
}
</style>