<template>
  <el-dialog
    custom-class="center-dialog"
    :title="title"
    top="0vh"
    :visible.sync="dialogFormVisible"
    width="950px"
    @close="close"
  >
    <el-scrollbar style="height: 600px">
      <template>
        <baidu-map
          :center="{ lng: center_lng, lat: center_lat }"
          class="map"
          :zoom="15"
        >
          <bm-marker
            animation="BMAP_ANIMATION_BOUNCE"
            :dragging="true"
            :position="{ lng: center_lng, lat: center_lat }"
          >
            <bm-label
              content=""
              :label-style="{ color: 'red', fontSize: '24px' }"
              :offset="{ width: -35, height: 30 }"
            />
          </bm-marker>
        </baidu-map>
      </template>
      <div class="admin_info">
        {{ __('管理员信息') }}
      </div>
      <el-form
        ref="form"
        :inline="true"
        label-width="80px"
        :model="form"
        :rules="chainRules"
      >
        <el-form-item
          :label="__('管理员账号')"
          label-width="90px"
          prop="user_account"
        >
          <el-input
            v-model="form.user_account"
            :placeholder="__('门店管理员账号')"
            style="width: 315px"
          />
        </el-form-item>
        <el-form-item
          :label="__('管理员密码')"
          label-width="120px"
          prop="user_password"
        >
          <el-input
            v-model="form.user_password"
            :placeholder="__('门店管理员密码')"
            style="width: 330px"
          />
        </el-form-item>
        <el-form-item
          :label="__('门店名称')"
          label-width="90px"
          prop="chain_name"
        >
          <el-input
            v-model="form.chain_name"
            :placeholder="__('门店名称')"
            style="width: 315px"
          />
        </el-form-item>
        <el-form-item
          :label="__('手机号码')"
          label-width="120px"
          prop="chain_mobile"
        >
          <el-input
            v-model="form.chain_mobile"
            :placeholder="__('手机号码')"
            style="width: 330px"
          />
        </el-form-item>
        <el-form-item
          :label="__('联系人')"
          label-width="90px"
          prop="chain_contacter"
        >
          <el-input
            v-model="form.chain_contacter"
            :placeholder="__('联系人')"
            style="width: 315px"
          />
        </el-form-item>
        <el-form-item
          v-if="false"
          :label="__('门店类型')"
          label-width="120px"
          prop="chain_category_id"
        >
          <el-cascader
            v-model="form.chain_category_id"
            :options="categoryTree"
            :props="categoryProps"
            :show-all-levels="false"
            :style="{ width: '153%' }"
          />
        </el-form-item>
        <div class="admin_info">
          {{ __('实体店铺详细地址') }}
        </div>
        <el-form-item
          :label="__('公司所在地')"
          label-width="90px"
          prop="chain_district_id"
        >
          <el-form-item>
            <Area v-model="queryArea" width="310" />
          </el-form-item>
        </el-form-item>
        <el-form-item
          :label="__('实体店铺详细地址')"
          label-width="130px"
          prop="chain_address"
        >
          <keyword
            :keyword="form.chain_address"
            :location="queryArea.city.name"
            :style="{ width: '160%' }"
            @getAddress="getAddress"
          />
        </el-form-item>
        <el-form-item :label="__('经度')" label-width="90px" prop="chain_lng">
          <el-input
            v-model="form.chain_lng"
            :placeholder="__('经度')"
            readonly
            style="width: 315px"
          />
        </el-form-item>
        <el-form-item :label="__('纬度')" label-width="140px" prop="chain_lat">
          <el-input
            v-model="form.chain_lat"
            :placeholder="__('纬度')"
            readonly
            style="width: 300px"
          />
        </el-form-item>
        <div v-if="false">
          <div class="admin_info">
            {{ __('详细信息') }}
          </div>
          <el-form-item
            :label="__('工位状态')"
            label-width="90px"
            prop="chain_job_state"
            required
          >
            <el-select
              v-model="form.chain_job_state"
              :placeholder="__('请选择')"
              style="width: 315px"
            >
              <el-option
                v-for="item in jobStateList"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item
            :label="__('服务项目')"
            label-width="140px"
            prop="chain_services"
            required
          >
            <el-select
              v-model="form.chain_services"
              :placeholder="__('请选择')"
              style="width: 300px"
            >
              <el-option
                v-for="item in chainProjectList"
                :key="item.chain_project_id"
                :label="item.chain_project_name"
                :value="item.chain_project_id"
              />
            </el-select>
          </el-form-item>
          <el-form-item
            :label="__('员工人数')"
            label-width="240px"
            prop="chain_staff_num"
            required
          >
            <el-input
              v-model="form.chain_staff_num"
              :placeholder="__('员工人数')"
              style="width: 300px"
            />
          </el-form-item>
          <el-form-item
            :label="__('工位数')"
            label-width="90px"
            prop="chain_job_num"
            required
          >
            <el-input
              v-model="form.chain_job_num"
              :placeholder="__('工位数')"
              style="width: 315px"
            />
          </el-form-item>
          <el-form-item
            :label="__('金牌技师数')"
            label-width="140px"
            prop="chain_good_staff_num"
            required
          >
            <el-input
              v-model="form.chain_good_staff_num"
              :placeholder="__('金牌技师数')"
              style="width: 300px"
            />
          </el-form-item>
          <el-form-item
            :label="__('服务数量')"
            label-width="90px"
            prop="chain_service_num"
            required
          >
            <el-input
              v-model="form.chain_service_num"
              :placeholder="__('服务数量')"
              style="width: 315px"
            />
          </el-form-item>
          <el-form-item
            :label="__('好评率')"
            label-width="140px"
            prop="chain_praise_rate"
            required
          >
            <el-input
              v-model="form.chain_praise_rate"
              :placeholder="__('好评率')"
              style="width: 300px"
            />
          </el-form-item>
        </div>
        <br />
        <el-form-item
          :label="__('门店图片')"
          label-width="90px"
          prop="chain_img"
          required
        >
          <upload
            height="100px"
            :image="form.chain_img"
            width="170px"
            @upImage="
              (image) => {
                form.chain_img = image
              }
            "
          />
        </el-form-item>
        <div class="sel_time">
          <el-form-item :label="__('营业时间')" prop="" required>
            <el-time-select
              v-model="form.chain_opening_hours"
              :picker-options="{
                start: '00:00',
                step: '00:05',
                end: '23:55',
              }"
              :placeholder="__('选择时间')"
              style="width: 200px"
            />
          </el-form-item>
          <el-form-item :label="__('关闭时间')" prop="" required>
            <el-time-select
              v-model="form.chain_close_hours"
              :picker-options="{
                start: '00:00',
                step: '00:05',
                end: '23:55',
              }"
              :placeholder="__('选择时间')"
              style="width: 200px"
            />
          </el-form-item>
        </div>
      </el-form>
    </el-scrollbar>
    <div slot="footer" class="dialog-footer">
      <el-button @click="close">{{ __('取消') }}</el-button>
      <el-button :loading="saveLoading" type="primary" @click="save">
        {{ __('确定') }}
      </el-button>
    </div>
  </el-dialog>
</template>

<script>
import { translateTitle as __ } from '@/utils/i18n'
import Area from '@/components/VabArea/area'
import keyword from '@/components/baiduMap/keyword'
import Upload from '@/components/upload'
import { doEdit } from '@/api/chain/base'
import { isPassword, isPhone } from 'vue-plugin-utils'
import { getCategoryTree } from '@/api/chain/category/base'
import { getList as getChainProjectList } from '@/api/chain/project/base'

export default {
  name: 'ChainBaseEdit',
  components: { Upload, keyword, Area },
  data() {
    const validatePhone = (rule, value, callback) => {
      if (!this.form.chain_mobile || !isPhone(this.form.chain_mobile)) {
        callback(new Error('请输入正确的手机号'))
      } else {
        callback()
      }
    }
    const validatePassword = (rule, value, callback) => {
      if (this.isAdd) {
        if (!value) {
          callback(new Error(this.__('请输入门店管理员密码')))
        } else if (!isPassword(value)) {
          callback(new Error(this.__('密码不能少于6位')))
        } else {
          callback()
        }
      } else {
        callback()
      }
    }
    return {
      form: {
        chain_img: '',
        chain_district_id: '',
        chain_district_info: '',
        chain_opening_hours: '',
        chain_close_hours: '',
        chain_lat: undefined,
        chain_lng: undefined,
      },
      categoryTree: [],
      categoryProps: {
        value: 'chain_category_id',
        label: 'chain_category_name',
        children: 'children',
        multiple: false,
        checkStrictly: true,
      },
      jobStateList: [
        {
          value: 201,
          label: '洗车适中',
        },
        {
          value: 202,
          label: '美容适中',
        },
        {
          value: 203,
          label: '保养适中',
        },
        {
          value: 204,
          label: '钣喷适中',
        },
      ],
      chainProjectList: [],
      map_show: false,
      center_lng: 116.404,
      center_lat: 39.915,
      rules: {},
      isAdd: true,
      saveLoading: false,
      title: '',
      formData: {
        pageNum: 1,
        pageSize: 9999,
      },
      dialogFormVisible: false,
      queryArea: {
        province: { code: '', name: '' },
        city: { code: '', name: '' },
        district: { code: '', name: '' },
      },
      chainRules: {
        user_account: [{ required: true, message: '门店管理员账号' }],
        chain_name: [{ required: true, message: '门店名称' }],
        chain_mobile: [
          {
            trigger: 'blur',
            message: '手机号码',
          },
          { validator: validatePhone, trigger: 'blur' },
        ],
        user_password: [
          {
            trigger: 'blur',
            message: '密码',
          },
          { validator: validatePassword, trigger: 'blur' },
        ],
        chain_contacter: [{ required: true, message: '联系人' }],
        // chain_category_id: [
        //   { required: true, message: '门店类型' },
        // ],
        chain_lng: [{ required: true, message: '经度' }],
        chain_lat: [{ required: true, message: '纬度' }],
        chain_opening_hours: [{ required: true, message: '营业时间' }],
        chain_close_hours: [{ required: true, message: '关闭时间' }],
        chain_img: [{ required: true, message: '门店图片' }],
      },
    }
  },
  created() {
    this.getCategoryTree()
    this.getChainProjectList()
  },
  mounted() {
    this.form = {
      unit_name: '',
    }
    this.$forceUpdate()
  },
  methods: {
    __,
    showEdit(row) {
      if (!row) {
        this.title = this.__('添加')
        this.isAdd = true
      } else {
        this.title = this.__('编辑')
        this.isAdd = false
        this.form = Object.assign({}, row)
        this.initData(row)
      }
      this.dialogFormVisible = true
    },
    initData(row) {
      this.form.chain_district_info = row.chain_district_info.split('/')
      this.form.chain_district_id = row.chain_district_id.split(',')
      this.echoAddress(row.chain_lng, row.chain_lat)
      this.initQueryArea(
        this.form.chain_district_id,
        this.form.chain_district_info
      )
    },

    initQueryArea(chain_district_id, chain_district_info) {
      if (!chain_district_id && chain_district_info) return
      if (chain_district_id[0]) {
        this.queryArea.province.code = chain_district_id[0]
      }
      if (chain_district_id[1]) {
        this.queryArea.city.code = chain_district_id[1]
      }
      if (chain_district_id[2]) {
        this.queryArea.district.code = chain_district_id[2]
      }
      if (chain_district_info[0]) {
        this.queryArea.province.name = chain_district_info[0]
      }
      if (chain_district_info[1]) {
        this.queryArea.city.name = chain_district_info[1]
      }
      if (chain_district_info[2]) {
        this.queryArea.district.name = chain_district_info[2]
      }
    },

    async getCategoryTree() {
      this.listLoading = true
      const { data } = await getCategoryTree(this.formData)
      this.categoryTree = data.items
      this.listLoading = false
    },

    async getChainProjectList() {
      this.listLoading = true
      this.formData.pageSize = 9999
      const { data } = await getChainProjectList(this.formData)
      if (data) {
        this.chainProjectList = data.items
      }
      this.formData.pageSize = 20
      this.listLoading = false
    },

    getAddress(address) {
      this.form.chain_address = address.value
      this.echoAddress(address.lng, address.lat)
    },

    // 回显地址
    echoAddress(lng, lat) {
      this.form.chain_lng = lng
      this.form.chain_lat = lat
      // 地图回显地位
      this.center_lng = lng
      this.center_lat = lat
    },

    close() {
      this.form.chain_img = null
      this.form.chain_opening_hours = null
      this.form.chain_close_hours = null
      ;(this.queryArea = {
        province: { code: '', name: '' },
        city: { code: '', name: '' },
        district: { code: '', name: '' },
      }),
        (this.form = this.$options.data().form)
      this.$refs['form'].resetFields()
      this.dialogFormVisible = false
    },
    save() {
      this.$refs['form'].validate(async (valid) => {
        if (valid) {
          let params = {}

          params = this.form

          delete params.chain_district_id

          if (this.queryArea.province.name) {
            params.chain_district_info = this.queryArea.province.name
          }
          if (this.queryArea.city.name) {
            params.chain_district_info += '/' + this.queryArea.city.name
          }
          if (this.queryArea.district.name) {
            params.chain_district_info += '/' + this.queryArea.district.name
          }

          if (this.queryArea.province.code) {
            params.chain_district_id = this.queryArea.province.code
          }
          if (this.queryArea.city.code) {
            params.chain_district_id += '/' + this.queryArea.city.code
          }
          if (this.queryArea.district.code) {
            params.chain_district_id += '/' + this.queryArea.district.code
          }

          // const chain_category_id =
          //   params.chain_category_id[
          //   params.chain_category_id.length - 1
          //     ]
          // params.chain_category_id = chain_category_id
          this.saveLoading = true
          const { msg, status } = await doEdit(params)
          if (200 == status) {
            this.$baseMessage(msg, 'success')
          } else {
            this.$baseMessage(msg, 'error')
          }
          this.saveLoading = false
          this.$emit('fetch-data')
          this.close()
        } else {
          return false
        }
      })
    },
  },
}
</script>
<style>
.map {
  width: 100%;
  height: 400px;
}
.admin_info {
  margin-top: 15px;
  font-size: 18px;
  color: #b1eca4;
}
.sel_time {
  float: right;
  width: 325px;
  margin-right: 10px;
}
</style>
