<template>
  <d2-container v-loading='isLoading'>
    <div class="addHouser-container">
      <el-form :model="form"
               label-width="120px"
               ref="form"
               :rules="rules">
        <el-form-item label="负责人："
                      prop="contactName">
          <el-input v-model="form.contactName"
                    placeholder="请填写"
                    autocomplete="off"
                    maxlength="30"
                    :show-word-limit="true"
                    class="filter-item-same-width" />
        </el-form-item>

        <el-form-item label="联系电话："
                      prop="contactPhone">
          <el-input v-model="form.contactPhone"
                    placeholder="请填写"
                    autocomplete="off"
                    maxlength="30"
                    :show-word-limit="true"
                    class="filter-item-same-width" />
        </el-form-item>
        <el-form-item label="联系邮箱："
                      prop="email">
          <el-input v-model="form.email"
                    placeholder="请填写"
                    autocomplete="off"
                    maxlength="30"
                    :show-word-limit="true"
                    class="filter-item-same-width" />
        </el-form-item>
        <el-form-item label="所在地区："
                      prop="a">
          <el-row :gutter="10"
                  style="width:800px">
            <el-col :span="5">
              <el-form-item label=""
                            prop="provinceId">
                <el-select v-model="form.provinceId"
                           :loading="isLoadProvinceId"
                           loading-text="信息加载中"
                           @change="provinceIdChange"
                           placeholder="选择省"
                           style="margin-left:-7px">
                  <el-option v-for="item in provinceIdList"
                             :key="item.id"
                             :label="item.name"
                             :value="item.id">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="5">
              <el-form-item label=""
                            prop="cityId">
                <el-select v-model="form.cityId"
                           @change="cityIdChange"
                           placeholder="选择市">
                  <el-option v-for="item in cityIdList"
                             :key="item.id"
                             :label="item.name"
                             :value="item.id"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="5">
              <el-form-item label=""
                            prop="countyId"
                            placeholder="选择区/县">
                <el-select v-model="form.countyId"
                           @change="fourChange">
                  <el-option v-for="item in countyIdList"
                             :key="item.id"
                             :label="item.name"
                             :value="item.id"></el-option>
                </el-select>
              </el-form-item>
            </el-col>

            <el-col :span="5"
                    v-if="isFourChage">
              <el-form-item label=""
                            prop="countyId"
                            placeholder="选择乡镇">
                <el-select v-model="form.townId">
                  <el-option v-for="item in fourIdList"
                             :key="item.id"
                             :label="item.name"
                             :value="item.id"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form-item>

        <el-form-item label="详细地址："
                      prop="addrDetail">
          <el-input v-model="form.addrDetail"
                    placeholder="请填写"
                    autocomplete="off"
                    maxlength="30"
                    :show-word-limit="true"
                    class="filter-item-same-width" />
        </el-form-item>
        <el-form-item label="营业时间："
                      prop="a"
                      style="width:600px">
          <el-col :span="11">
            <el-select v-model="startWeek"
                       placeholder="请选择">
              <el-option v-for="item in weekList"
                         :key="item.value"
                         :label="item.label"
                         :value="item.value">
              </el-option>
            </el-select>
          </el-col>
          <el-col :span="2"
                  class="line">至</el-col>
          <el-col :span="11">
            <el-select v-model="endWeek"
                       placeholder="请选择">
              <el-option v-for="item in weekList"
                         :key="item.value"
                         :label="item.label"
                         :value="item.value">
              </el-option>
            </el-select>
          </el-col>
        </el-form-item>
        <el-form-item label=""
                      prop="name"
                      style="width:600px">
          <el-col :span="11">
            <el-select v-model="startTime"
                       placeholder="请选择">
              <el-option v-for="item in timeList"
                         :key="item.value"
                         :label="item.label"
                         :value="item.value">
              </el-option>
            </el-select>
          </el-col>
          <el-col :span="2"
                  class="line">-</el-col>
          <el-col :span="11">
            <el-select v-model="endTime"
                       placeholder="请选择">
              <el-option v-for="item in timeList"
                         :key="item.value"
                         :label="item.label"
                         :value="item.value">
              </el-option>
            </el-select>
          </el-col>
        </el-form-item>
      </el-form>
    </div>
    <span slot="footer"
          class="dialog-footer">
      <el-button @click="cancel">取消</el-button>
      <el-button type="primary"
                 style="margin-left: 150px"
                 :loading="ifSubmit"
                 @click="submit('form')">保存</el-button>
    </span>
  </d2-container>
</template>

<script>
import { mapState, mapActions } from 'vuex'
import {
  getBusiness,
  jdAddressCascader,
  modiyBusiness
} from '@/libs/common/constant'
import { selectList, generateTiemList, weekList } from '@/utils/json'

export default {
  data () {
    return {
      openId: this.$route.params.id,
      isLoading: false,
      isLoadProvinceId: false,
      // 一级
      provinceIdList: [],
      // 二级
      cityIdList: [],
      // 三级
      countyIdList: [],
      // 四级
      fourIdList: [],
      isFourChage: false,
      ifSubmit: false,
      weekList: [],
      timeList: [],
      startWeek: '',
      endWeek: '',
      startTime: '',
      endTime: '',
      form: {
        startWeek: '',
        endWeek: '',
        startTime: '',
        endTime: ''
      },
      rules: {
        email: [{ required: true, message: '请填写', trigger: 'blur' }],
        addrDetail: [{ required: true, message: '请填写', trigger: 'blur' }],
        contactPhone: [{ required: true, message: '请填写', trigger: 'blur' }],
        contactName: [{ required: true, message: '请填写', trigger: 'blur' }],
        a: [{ required: true, message: '请填写', trigger: 'blur' }],
        provinceId: [{ required: true, message: '请选择', trigger: 'change' }],
        cityId: [{ required: true, message: '请选择', trigger: 'change' }],
        countyId: [{ required: true, message: '请选择', trigger: 'change' }]
      }
    }
  },
  async created () {
    if (this.openId) {
      this.isLoading = true
      await this.getBusiness()
      await this.getConstant()
    }
  },
  computed: {
    // 获取 此页面 路径
    ...mapState('d2admin/page', ['current'])
  },
  methods: {
    ...mapActions('d2admin/page', ['close', 'add']),
    // 获取基本信息
    async getBusiness () {
      const res = await this.$api.GET(`${getBusiness.url}${this.openId}`)
      this.form = { ...res.info, ...res.company }
      const arr = [...this.form.businessHours]
      this.startWeek = arr[1]
      this.endWeek = arr[4]
      this.startTime = arr[6] + arr[7]
      this.endTime = arr[12] + arr[13]
      this.provinceIdList = await this.getProvinceList()
      this.cityIdList = await this.getCityList(this.form.provinceId)
      this.countyIdList = await this.getCountyId(this.form.cityId)
      if (this.form.townId) {
        this.fourIdList = await this.getfourList(this.form.countyId)
        this.isFourChage = true
      } else {
        this.isFourChage = false
      }
      console.log(this.form)
      this.form.a = '1111'
      this.isLoading = false
    },
    async getConstant () {
      this.timeList = await this.generateTiemList()
      this.weekList = await this.weekLista()
    },
    // 获取 一级地址
    async getProvinceList () {
      const res = await this.$api.GET(`${jdAddressCascader.url}`)
      this.isLoadProvinceId = false
      return res
    },
    // 获取 二级 地址
    async getCityList (provinceId) {
      const res = await this.$api.GET(`${jdAddressCascader.url2}${provinceId}`)
      return res
    },
    // 获取 三级 地址
    async getCountyId (cityId) {
      const res = await this.$api.GET(`${jdAddressCascader.url3}${cityId}`)
      return res
    },
    // 获取 四级 地址
    async getfourList (countyId) {
      const res = await this.$api.GET(`${jdAddressCascader.url4}${countyId}`)
      console.log(res, '我被调用了')
      return res
    },
    // 二级地址赋值
    async provinceIdChange () {
      this.cityIdList = await this.getCityList(this.form.provinceId)
      this.form.cityId = ''
      this.form.countyId = ''
    },
    // 三级 地址 赋值
    async cityIdChange () {
      this.countyIdList = await this.getCountyId(this.form.cityId)
      this.form.countyId = ''
    },
    // 四级 地址 赋值
    async fourChange () {
      this.fourIdList = await this.getfourList(this.form.countyId)
      // return
      // if (this.fourIdList.length > 0) {
      //   this.isFourChage = true
      //   this.form.townId = ''
      // } else {
      //   this.isFourChage = false
      //   this.form.townId = 0
      // }
    },
    selectList (myJson, a) {
      return selectList(myJson, a)
    },
    weekLista () {
      return weekList
    },
    generateTiemList () {
      return generateTiemList()
    },
    async cancel () {
      var tagName = this.current
      await this.close({ tagName })
      this.$router.push('/businessList')
    },
    validatePhoneNumber (phoneNumber) {
      var pattern = /^1[3456789]\d{9}$/
      return pattern.test(phoneNumber)
    },
    submit (detail) {
      if (!this.validatePhoneNumber(this.form.contactPhone)) {
        this.$message.error('请输入正确的手机号！！！')
        return
      }
      if (this.ifSubmit) {
        return
      }
      this.ifSubmit = true
      this.$refs[detail].validate(async (valid) => {
        if (valid) {
          try {
            // 提交前 处理 数据
            // 拼接 营业时间 转换 时间
            var data = await this.arrangeData()
            // 判断 参数 确定是修改还是 添加
            if (this.openId) {
              console.log(data, '编辑提交的参数')
              //  提交接口
              data.companyOpenId = this.openId
              const res = await this.$api.POST(`${modiyBusiness.url}`, data)
              console.log(res)
            } else {
              console.log(data, '添加提交的参数')
            }
            await this.cancel()
            this.$message({
              type: 'success',
              message: '操作成功!'
            })
          } catch (error) {}
        } else {
          console.log('error submit!!')
          this.ifSubmit = false
          return false
        }
      })
    },
    arrangeData () {
      if (this.startWeek) {
        this.form.businessHours = `周${this.startWeek}至周${this.endWeek},${this.startTime}:00至${this.endTime}:00`
      }
      // if (this.form.validUntil != this.form.value1) {
      //   this.form.validUntil = dayjs(this.form.value1).format(
      //     "YYYY-MM-DD 00:00:00"
      //   );
      // }
      // this.form.validUntil = "2025-01-15 00:00:00";
      var data = {
        companyName: this.form.companyName,
        provinceId: this.form.provinceId,
        cityId: this.form.cityId,
        countyId: this.form.countyId,
        townId: this.form.townId,
        contactName: this.form.contactName,
        contactPhone: this.form.contactPhone,
        loginName: this.form.loginName,
        loginPwd: this.form.loginPwd,
        merchantId: this.form.merchantId,
        merchantName: this.form.merchantName,
        nature: this.form.nature,
        businessType: this.form.businessType,
        validUntil: this.form.validUntil,
        payRate: this.form.payRate,
        serviceRate: this.form.serviceRate,
        addrDetail: this.form.addrDetail,
        businessHours: this.form.businessHours,
        email: this.form.email,
        // 非必填
        companyCode: this.form.companyCode,
      }
      if(this.form.businessLicenseImageList){
       data.businessLicenseImageList = this.form.businessLicenseImageList
      }
      return data
    }
  }
}

</script>

<style>
</style>
