<template>
  <el-dialog
    :title="title"
    :visible.sync="dialogVisible"
    width="750px"
    :append-to-body="true"
    :before-close="close"
    :destroy-on-close="true"
    :close-on-click-modal="false"
  >
    <el-form
      ref="form"
      :model="form"
      :rules="rules"
      label-width="120px"
      label-position="top"
      style="max-height: 375px;overflow: auto;"
    >
    <flexbox class="ygp-form-items" align="flex-start" justify="flex-start">
      <el-form-item label="渠道名称" prop="name" style="width: 50%;">
        <el-input v-model="form.name" placeholder="请输入渠道名称" />
      </el-form-item>
       <el-form-item label="手机号码" prop="mobile" style="width: 50%;">
         <el-input v-model="form.mobile" placeholder="请输入手机号码" />
       </el-form-item>
    </flexbox>
      <!-- <flexbox class="ygp-form-items" align="flex-start" justify="flex-start">
        <el-form-item label="上级渠道" prop="parentId" style="width: 50%;">
          <el-select
            v-model="form.parentId"
            placeholder="请选择上级渠道"
            style="width: 100%;"
            filterable
            clearable
            :filter-method="dataFilter"
          >
            <el-option
              v-for="(item, index) in channelList"
              :key="item.channelId"
              :label="item.name"
              :value="item.channelId">
              <div>
                <span style="float: left;">{{item.name}} </span>
                <span style="float: right;">{{item.mobile}}</span>
              </div>
            </el-option>
          </el-select>
        </el-form-item>
      </flexbox> -->
      <flexbox class="ygp-form-items" align="flex-start" justify="flex-start">
        <el-form-item label="联系人" prop="contact" style="width: 50%;">
          <el-input v-model="form.contact" placeholder="联系人" />
        </el-form-item>
        <el-form-item label="佣金比例" prop="commRate" style="width: 50%;">
          <el-input v-model="form.commRate" placeholder="请输入佣金比例" />
        </el-form-item>
      </flexbox>
      <flexbox class="ygp-form-items" align="flex-start" justify="flex-start">
        <el-form-item label="省" prop="provinceId" style="width: 30%;">
          <el-select
            v-model="form.provinceId"
            placeholder="选择省份"
            clearable
            size="small"
            @change="getCityList()"
            style="width: 100%;margin-right: 1px;">
            <el-option
              v-for="item in provinceList"
              :key="item.areaId"
              :label="item.areaName"
              :value="item.areaId"
            />
          </el-select>

        </el-form-item>
        <el-form-item label="市" prop="cityId" style="width: 30%;">
          <el-select
            v-model="form.cityId"
            placeholder="选择市"
            clearable
            size="small"
             @change="getAreaList()"
            style="width: 100%;margin-right: 1px;">
            <el-option
              v-for="item in cityList"
              :key="item.areaId"
              :label="item.areaName"
              :value="item.areaId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="区" prop="areaId" style="width: 30%;" >
          <el-select v-model="form.areaId"
            placeholder="选择区"
            clearable
            size="small"
            @change="getAreaName()"
            style="width: 100%;margin-right: 1px;">
            <el-option
              v-for="item in areaList"
              :key="item.areaId"
              :label="item.areaName"
              :value="item.areaId"
            />
          </el-select>
        </el-form-item>
      </flexbox>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button @click="close">取 消</el-button>
      <el-button type="primary" :disabled="loading" @click="saveClick">确 定</el-button>
    </div>
  </el-dialog>
</template>
<script>
import { addChannel, updateChannel, listAllChannel, getChannelDetail} from "@/api/admin/channel";
import { listAreaByPid} from "@/api/admin/area";
import { mapGetters } from "vuex";
export default {
  props: {
    dialogVisible: {
      type: Boolean,
      default: false
    },
    editId: [Number, String] //  编辑用
  },

  data() {
    return {
      loading: false,
      // 上级渠道列表
      channelList:[],
      channelCopyList:[],
      provinceList:[],
      cityList:[],
      areaList:[],
      statusOptions: [],
      // 表单参数
      form: {
        name:"",
        mobile:"",
        contact:"",
        commRate:"",
        provinceId:"",
        cityId:"",
        areaId:"",
        province:"",
        city:"",
        area:""
      },
      detail: {},
      // 表单校验
      rules: {
        name: [
          { required: true, message: "请输入渠道名称", trigger: "blur" }
        ],
        mobile: [
          { required: true, message: "请输入手机号码", trigger: "blur" },
          {pattern: /^((\+?86)|(\(\+86\)))?1\d{10}$/, message: "请输入正确的手机号码", trigger: "blur" }
        ],
        // parentId: [{ required: true, message: "请选择上级渠道", trigger: "change" }],
        contact: [
          { required: true, message: "请输入联系人", trigger: "blur" }
        ],
        commRate: [
          { required: true, message: "请输入佣金比例", trigger: "blur" },
          { pattern: /^(([1-9]{1}\d{0,99}))(\.\d{1,2})?$/, message: "佣金比例只能为大于0的数字", trigger:['blur', 'change'] },
        ],
        provinceId: [{ required: true, message: "请选择省", trigger: "change" }],
        cityId: [{ required: true, message: "请选择市", trigger: "change" }],
        areaId: [{ required: true, message: "请选择区", trigger: "change" }],

      },
      //招商推广宣传图
      picture: []
    };
  },

  computed: {
    ...mapGetters(["userInfo"]),
    title() {
      return this.editId ? "编辑一级渠道" : "添加一级渠道";
    }
  },

  created() {
    //this.getCustItems();
   // this.getTypeItems();
    //console.log("watch dialogVisible created == ");
    // 是编辑
    if (this.editId) {
       this.getDetail();
    }else{
       this.getProvinceList()
    }
    // this.getChannelList()

  },

  mounted() {
    document.body.appendChild(this.$el);
  },

  destroyed() {
    // if appendToBody is true, remove DOM node after destroy
    if (this.appendToBody && this.$el && this.$el.parentNode) {
      this.$el.parentNode.removeChild(this.$el);
    }
  },

  methods: {

    // 获取上级渠道下拉列表
    getChannelList(){
      listAllChannel().then(response => {
        var noneObj = {
          channelId:0,
          name:'无(新建一级渠道)'
          }
          this.channelList.push(noneObj)
        // console.log("getChannelList == "+ JSON.stringify(response.data))
         this.channelList = this.channelList.concat(response.data || []);
         this.channelCopyList = this.channelList;
      });
    },
    // 省
    getProvinceList(){
      this.cityList = []
      this.areaList = []
      this.form.cityId = ""
      this.form.city = ""
      this.form.areaId = ""
      this.form.area = ""
      listAreaByPid(0).then(response => {
        // console.log("getProvinceList"+JSON.stringify(response))
         console.log("getProvinceList this.form=="+JSON.stringify(this.form))
         this.provinceList = response || [];
          console.log("this.editId && this.form.provinceId == "+(this.editId && this.form.provinceId))
         if(this.editId && this.detail.provinceId){
            this.form.provinceId = this.detail.provinceId
            this.getCityList()
         }
      });
    },

    getProvinceName(){
      let val = this.form.provinceId
      if(val){
        let nameObj = this.provinceList.find(item => {
              return item.areaId == val;
        })
        return nameObj && nameObj.areaName
      }
      return ""
    },


    getCityList(){
      this.cityList = []
      this.areaList = []
      this.form.cityId = ""
      this.form.city = ""
      this.form.areaId = ""
      this.form.area = ""
      var provinceId = this.form.provinceId
      this.form.province = this.getProvinceName()
      listAreaByPid(provinceId).then(response => {
         this.cityList = response || [];
         if(this.editId && this.detail.cityId){
            this.form.cityId = this.detail.cityId
            this.getAreaList()
         }
      });

    },

    getCityName(){
      let val = this.form.cityId
      if(val){
        let nameObj = this.cityList.find(item => {
              return item.areaId == val;
        })
        return nameObj && nameObj.areaName
      }
      return ""
    },

    getAreaList(){
      var cityId = this.form.cityId
      this.form.city = this.getCityName();
      listAreaByPid(cityId).then(response => {
        // console.log("getAreaList"+JSON.stringify(response))
         this.areaList = response || [];
         if(this.editId && this.detail.areaId){
            this.form.areaId = this.detail.areaId
         }
      });
    },

    getAreaName(){
      let val = this.form.areaId
      if(val){
        let nameObj = this.areaList.find(item => {
              return item.areaId == val;
        })
        this.form.area = nameObj && nameObj.areaName
      }else{
        this.form.area = "";
      }
    },

    dataFilter(val) {
      this.value = val;
      if (val) { //val存在
        this.channelList = this.channelCopyList.filter((item) => {
          // console.log("dataFilter item"+JSON.stringify(item))
          if (!!~item.mobile.indexOf(val) || !!~item.mobile.toUpperCase().indexOf(val.toUpperCase())) {
             return true
          }
        })
      } else { //val为空时，还原数组
        this.channelList = this.channelCopyList;
      }
    },


    /**
     * 获取项目详情
     */
    getDetail() {
      this.loading = true;
      getChannelDetail(this.editId).then(res => {
          const data = res.data || {}
          // console.log("getDetail :" + JSON.stringify(data))
          this.detail = data
          this.form.name = data.name
          this.form.mobile = data.mobile
          this.form.contact = data.contact
          this.form.commRate = data.commRate
          this.loading = false
          this.getProvinceList()
        })
        .catch(() => {
          this.loading = false;
        });
    },


    saveClick(){
      // console.log("saveClick tthis.form = "+JSON.stringify(this.form))
      this.loading = true
      const subForm = this.$refs["form"]
      subForm.validate(valid => {
        if (valid) {
          this.submitForm(this.form);
        } else {
          this.loading = false;
          // 提示第一个error
          this.getFormErrorMessage(subForm);
          return false;
        }
      });
    },

    /**
     * 保存
     */
    submitForm(params) {
      //  console.log("submitForm =============")
      if (this.editId) {
        params.channelId = this.editId;
      }
      const request = this.editId ? updateChannel : addChannel
      // console.log("submitForm params = "+ JSON.stringify(params))
      request(params).then(response => {
        this.loading = false
        if(this.editId){
           this.$message.success('更新成功')
        }else{
           this.$message.success('新增成功')
        }
        this.$emit('saveSuccess')
        this.close()
      }).catch(() => {
        this.loading = false
      });
    },

    /**
     * 关闭窗口
     */
    close() {
      this.$emit("close");
      this.form = {
        month: 3,
        packageType: "1"
      };
    }
  }
};
</script>

<style scoped lang="scss">
.tag {
  margin-right: 15px;
  width: 90px;
  text-align: center;
  cursor: pointer;
}

.tag-select {
  background-color: #409eff !important;
  border-color: #409eff !important;
  color: #fff !important;
}

.cover-content-item {
  width: 220px;
  float: left;
  position: relative;
  .cover-img {
    width: 200px;
    height: 100px;
  }
  .cover-mark {
    position: absolute;
    top: 0px;
    right: 28px;
    z-index: 1;
    color: red;
    cursor: pointer;
    visibility: hidden;
  }
  .select {
    visibility: visible !important;
  }
}

.dialog-footer {
  text-align: center;
}
</style>

<style lang="scss">
.ygp-form-items {
  .el-form-item {
    padding: 0 5px;
  }
  .el-form-item__label {
    line-height: 1.2;
    padding-bottom: 8px;
    word-break: break-all;
    word-wrap: break-word;
    color: #333;
  }

  .el-form-item__error {
    position: relative;
    top: auto;
    left: auto;
  }

  .el-form-item.is-desc_text {
    .el-form-item__label {
      display: none;
    }
  }
}
</style>
