<template>
  <div class="addUser app-container">
    <el-form
      :model="setQuery"
      ref="setQuery"
      :rules="rules"
      label-width="130px"
    >
      <el-form-item label="商户类型：" prop="accountChildType">
        <el-select
          v-model="setQuery.accountChildType"
          size="small"
          clearable
          class="item-width-300"
          placeholder="请选择"
        >
          <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-item label="绑定主商户" prop="platformType">
          <el-checkbox-group v-model="setQuery.platformType">
            <div class="flex" v-for="(item,index) in masterShopOptions" :key="index" ><el-checkbox :label="item.value">{{item.label}}</el-checkbox> 
            <el-form-item v-if="setQuery.platformType.includes(item.value)" :prop="'platformShareLists.' + index + '.shareId'" :rules="{required: true, message: '请选择分账规则', trigger: 'change'}">
              <el-select
                v-model="setQuery.platformShareLists[index].shareId"
                class="item-width-300"
                size="small"

                placeholder="请选择商品分账规则"
              >
                <el-option
                  v-for="item in ruleOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                >
                </el-option>
              </el-select>
            </el-form-item>
            </div>
   
            <!-- <el-checkbox label="1">慧研学惠生活</el-checkbox>
            <el-checkbox label="2" >印象贵大</el-checkbox> -->
          </el-checkbox-group>
        </el-form-item>
      <el-form-item label="商户名称：" prop="accountName">
        <el-input
          v-model="setQuery.accountName"
          size="small"
          class="item-width-300"
        ></el-input>
      </el-form-item>
      <el-form-item label="所在地区：" prop="district">
         <el-select
          v-model="setQuery.province"
          size="small"
          clearable
          class="item-width-150"
          placeholder="请选择省"
        >
          <el-option
            v-for="item in provinceList"
            :key="item.code"
            :label="item.name"
            :value="item.code"
          >
          </el-option>
        </el-select>
        <el-select
          v-model="setQuery.city"
          size="small"
          clearable
          class="item-width-150 ml10"
          placeholder="请选择市"
        >
          <el-option
            v-for="item in cityList"
             :key="item.code"
            :label="item.name"
            :value="item.code"
          >
          </el-option>
        </el-select>
        <el-select
          v-model="setQuery.district"
          size="small"
          clearable
          class="item-width-150 ml10"
          placeholder="请选择区"
        >
          <el-option
            v-for="item in countyList"
            :key="item.code"
            :label="item.name"
            :value="item.code"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="联系人：" prop="contactName">
        <el-input
          v-model="setQuery.contactName"
          size="small"
          class="item-width-300"
        ></el-input>
      </el-form-item>
      <el-form-item label="手机号：" prop="phoneNum">
        <el-input
          v-model="setQuery.phoneNum"
          :maxlength="11"
          size="small"
          class="item-width-300"
           :disabled="!!this.$route.query.id"
        ></el-input>
      </el-form-item>
      <!-- <el-form-item label="商品分账规则：" prop="shareId">
        <el-select
          v-model="setQuery.shareId"
          class="item-width-300"
          placeholder="请选择商品分账规则"
        >
          <el-option
            v-for="item in ruleOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          >
          </el-option>
        </el-select>
      </el-form-item> -->
      <el-form-item label="备注：" prop="notes">
        <el-input
          v-model="setQuery.notes"
          class="item-width-300"
          type="textarea"
        ></el-input>
      </el-form-item>
    </el-form>

    <div class="btn-group">
      <el-button>取 消</el-button>
      <el-button type="primary" :loading="loading" @click="save"
        >确 定</el-button
      >
    </div>
  </div>
</template>

<script>
import { getShopType,addOrUpdateAccount,accountDetail } from "@/api/user";
import {getRegion} from '@/api/payment';
import {debounce} from '@/utils/index';
import {getRuleList} from '@/api/rule'

export default {
  data() {
    var validatePhone = (rule, value, callback) => {
      let reg = /^[1][3,4,5,6,7,8,9][0-9]{9}$/
        if (value && reg.test(value)) {
            callback();
        }else{
           callback(new Error('手机号不合法'));
        }
      };
    return {
        loading:false,
      setQuery: {
        accountChildType: "",
        accountId: "",
        accountName: "",
        accountType: "202",//商户202  渠道201
        address: "",
        city: "",
        contactName: "",
        district: "",
        mapLat: "",
        mapLon: "",
        notes: "",
        phoneNum: "",
        province: "",
        shareId:'',
        platformType:[],
        platformShareLists:[]
      },
      region:{
        "code": "",
        "type": "province"
      },
      rules: {
        accountName: [{ required: true, message: "请输入账户名称", trigger: "blur" }],
        accountChildType: [
          { required: true, message: "请选择账户类型", trigger: "change" },
        ],
        shareId: [
          { required: true, message: "请选择商品分账规则", trigger: "change" },
        ],
        contactName: [
          { required: true, message: "请输入联系人", trigger: "blur" },
        ],
        phoneNum: [
          { required: true, message: "请输入手机号", trigger: "blur" },
            { validator: validatePhone, trigger: 'blur' }
        ],
        platformType: [
          { type: 'array', required: true, message: '请至少绑定一个主商户', trigger: 'change' }
        ],
        // notes: [
        //   { required: true, message: "请输入备注", trigger: "blur" },
        // ],
      },
      isInit:false,
      options: [],
      provinceList: [],//省
      cityList: [],//市
      countyList: [],//区
      ruleOptions:[],
      
    };
  },
  watch: {
    'setQuery.province':debounce(function(val) {
      if(val){
        this.getRegion('city',val)
      }
      if(!this.isInit){
        console.log(this.isInit);

        this.setQuery.city = ''
        this.setQuery.district = ''
        this.cityList = []
        this.countyList = []
      }
    }),
    'setQuery.city':debounce(function(val) {
      if(val){
        this.getRegion('county',val)
      }
      if(!this.isInit){
        console.log(this.isInit);
        this.setQuery.district = ''
        this.countyList = []
      }
    }),
    // 'setQuery.platformType'(val) {
    //   console.log(123);
    // }
  },
  methods: {
    // 获取地区数据
    getRegion(type,code=''){
      getRegion({type,code}).then(res=>{
        if (res.state == "Success") {
          this[type+'List'] = res.content
        }
      })
    },
    getShopType() {
      getShopType().then((res) => {
        if (res.state == "Success") {
          for (const key in res.content) {
            if (Object.hasOwnProperty.call(res.content, key)) {
              this.options.push({
                value: key,
                label: res.content[key],
              });
            }
          }
        }
      });
    },
    accountDetail(accountId) {
      this.isInit = true
      accountDetail({accountId}).then((res) => {
        if (res.state == "Success") {
          this.setQuery = res.content
          this.$set(this.setQuery,'platformShareLists',[])
          this.masterShopOptions.map(item=>{
            this.setQuery.platformShareLists.push({
              shareId:'',
              platformType:item.value
            })
          })
          let platformShareLists = JSON.parse(this.setQuery.platformShares)
          platformShareLists.map(item=>{
            this.setQuery.platformShareLists.map(i=>{
              if(item.platformType == i.platformType){
                i.shareId = item.shareId
              }
            })
          })
          this.setQuery.platformType = this.setQuery.platformType.split(',').map(Number)

          setTimeout(() => {
            this.isInit = false
          }, 1000);
         
        }
      });
    },
    // 规则
    getRuleList() {
      getRuleList({currentPage:1,pageSize:999}).then((res) => {
        if (res.state == "Success") {
          res.content.records.map(item=>{
            this.ruleOptions.push({
              label:item.shareRule,
              value:item.id
            })
          })
        }
      });
    },
    
     save() {
         this.$refs.setQuery.validate((v) => {
             if (v) {
            this.loading = true;
            let obj = JSON.parse(JSON.stringify(this.setQuery))
            if(this.$route.query.id){
              delete obj.phoneNum
            }
            let platformShareLists = JSON.parse(JSON.stringify(obj.platformShareLists))
            obj.platformShareLists = []
            platformShareLists.map((item,index)=>{
              if(item.shareId&&obj.platformType.includes(item.platformType)){
                obj.platformShareLists.push(item)
              }
            
            })
            obj.platformType = obj.platformType.toString()

          addOrUpdateAccount(obj).then((res) => {
            this.loading = false;
            if (res.state == "Success") {
              this.$notify({
                title: "成功",
                message: "操作成功",
                type: "success",
              });
              this.setQuery = {
                accountChildType: "",
                accountId: "",
                accountName: "",
                accountType: "202",
                address: "",
                city: "",
                contactName: "",
                district: "",
                mapLat: "",
                mapLon: "",
                notes: "",
                phoneNum: "",
                province: "",
                platformType:[],
                platformShareLists:[]
              };
              this.$router.push("/merchantManage/index");
            }
          });
        }
      });
    },
  },

  created() {
    this.setQuery.platformShareLists=[]
    this.masterShopOptions.map(item=>{
      this.setQuery.platformShareLists.push({
        shareId:'',
        platformType:item.value
      })
    })
    this.getRuleList()
    if(this.$route.query.title == '编辑商户'){
      // this.setQuery = JSON.parse( sessionStorage.getItem('shopUser') )
      this.accountDetail(this.$route.query.id)
    }
    this.getShopType();
    this.getRegion('province');
  },
};
</script>

<style lang="scss" scoped>
.addUser {
     padding-bottom: 40px;
     .flex{
      width: 500px;
      display: flex;
      align-items: center;
      justify-content: space-between;
     }
  .btn-group {
    display: flex;
    align-items: center;
    justify-content: center;
  }
}
</style>