<template>
  <div class="app-container">
    <div class="search-con">
      <div class="title">查询条件</div>
      <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="100px">
        <el-form-item label="手机号" prop="mobile">
          <el-input v-model="queryParams.mobile" placeholder="请输入手机号" clearable @keyup.enter="handleQuery" />
        </el-form-item>
      </el-form>
      <div class="search-btn-con">
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button type="info" icon="Refresh" @click="resetQuery">重置</el-button>
      </div>
    </div>
    <div class="main-con">
      <div class="title-con">
        <div class="title">基本信息</div>
        <div class="operate-btn-con">
          <el-button @click="handleAddIUser" icon="Plus" v-hasPermi="['invest:iuser:add']">添加账号</el-button>
          <el-button :disabled="multiple" icon="Delete" @click="handleDelete" v-hasPermi="['invest:iuser:remove']">删除</el-button>
        </div>
      </div>
      <div class="content-con" v-loading="loading">
        <el-table v-loading="loading" :data="iuserList" @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="55" align="center" />
          <el-table-column label="手机号" width="120" align="center" prop="mobile" />
          <el-table-column label="姓名" width="100" align="center" prop="userName" />
          <el-table-column label="预约商品" align="center" prop="itemName" />
          <el-table-column label="默认预约门店" align="center" prop="shopName" />
          <el-table-column label="预约类型" align="center" prop="shopType">
            <template #default="scope">
              <dict-tag :options="reservation_type" :value="scope.row.shopType" />
            </template>
          </el-table-column>
          <el-table-column label="随机时间预约" width="120" align="center" prop="randomMinute">
            <template #default="scope">
              <dict-tag :options="open_close" :value="scope.row.randomMinute" />
            </template>
          </el-table-column>
          <el-table-column label="到期时间" align="center" prop="expireTime" width="160"> </el-table-column>
          <el-table-column label="操作" align="center" width="400" class-name="small-padding fixed-width">
            <template v-slot="scope">
              <div class="ctrl-btn d-flex">
                <el-tooltip v-for="item in operateList" :key="item.id" class="item" effect="dark" :content="item.title" placement="top">
                  <el-button v-hasPermi="item.hasPermi" @click="handleOperate(item.id, scope.row)">{{ item.name }}</el-button>
                </el-tooltip>
              </div>
            </template>
          </el-table-column>
        </el-table>
        <el-pagination small background layout="total, prev, pager, next" :total="total" @current-change="handleCurrentChange" />
      </div>
    </div>
    <!-- 添加或修改账号管理对话框 -->
    <el-dialog :title="title" v-model="open" width="880px" append-to-body>
      <el-form ref="iuserRef" :model="form" :rules="rules" label-width="120px" :inline="true">
        <el-form-item label="用户id" prop="userId">
          <el-input readonly v-model="form.userId" placeholder="请输入用户id" />
        </el-form-item>
        <el-form-item label="手机号" prop="mobile">
          <el-input readonly v-model="form.mobile" placeholder="请输入手机号" />
        </el-form-item>
        <el-form-item label="预约商品" prop="itemCode">
          <el-select v-model="itemSelect" multiple placeholder="请选择预约商品" @change="changeItem">
            <el-option v-for="item in itemList" :key="item.itemCode" :label="item.itemCodeTitle" :value="item.itemCode"> </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="省份" prop="provinceName">
          <el-select v-model="form.provinceName" placeholder="请选择省份" @change="handleProvinceChange" clearable>
            <el-option v-for="district in provinceList" :key="district.provinceName" :label="district.provinceName" :value="district.provinceName" />
          </el-select>
        </el-form-item>
        <el-form-item label="城市" prop="cityName">
          <el-select v-model="form.cityName" placeholder="请选择城市" @change="handleCityChange" clearable>
            <el-option v-for="district in cityList" :key="district.cityName" :label="district.cityName" :value="district.cityName" />
          </el-select>
        </el-form-item>
        <el-form-item label="区域" prop="districtName">
          <el-select v-model="form.districtName" placeholder="请选择区域" @change="handleDistrictChange" clearable>
            <el-option v-for="district in districtList" :key="district.districtName" :label="district.districtName" :value="district.districtName" />
          </el-select>
        </el-form-item>
        <el-form-item label="默认预约门店" prop="ishopId">
          <el-select v-model="form.ishopId" placeholder="请选择默认预约门店" clearable>
            <el-option v-for="shop in ishopList" :key="shop.ishopId" :label="shop.name" :value="shop.ishopId" />
          </el-select>
        </el-form-item>
        <el-form-item label="预约类型" prop="shopType">
          <el-select v-model="form.shopType" placeholder="请选择预约类型">
            <el-option v-for="dict in reservation_type" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="随机时间预约" prop="randomMinute">
          <el-select v-model="form.randomMinute" placeholder="请选择随机时间预约">
            <el-option v-for="dict in open_close" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="预约执行分钟" prop="minute">
          <el-input v-model="form.minute" placeholder="请输入预约执行分钟" />
        </el-form-item>
      </el-form>
      <template v-if="title !== '查看账号管理'" #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <el-dialog title="添加账号" v-model="openUser" width="880px" append-to-body>
      <el-form ref="formIuser" :rules="addRules" label-width="120px" :inline="true" :model="form">
        <el-form-item label="手机号" prop="mobile">
          <el-input v-model="form.mobile" placeholder="请输入I茅台用户手机号" />
        </el-form-item>
        <el-form-item label="">
          <el-button type="primary" @click="sendMobileCode(form.mobile)"
            >发送验证码<span v-if="state">({{ stateNum }})</span>
          </el-button>
        </el-form-item>
        <el-form-item label="验证码" prop="code">
          <el-input v-model="form.code" placeholder="请输入验证码" />
        </el-form-item>
        <el-form-item label="预约商品" prop="itemCode">
          <el-select v-model="itemSelect" multiple placeholder="请选择预约商品" @change="changeItem">
            <el-option v-for="item in itemList" :key="item.itemCode" :label="item.itemCodeTitle" :value="item.itemCode"> </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="省份" prop="provinceName">
          <el-select v-model="form.provinceName" placeholder="请选择省份" @change="handleProvinceChange" clearable>
            <el-option v-for="district in provinceList" :key="district.provinceName" :label="district.provinceName" :value="district.provinceName" />
          </el-select>
        </el-form-item>
        <el-form-item label="城市" prop="cityName">
          <el-select v-model="form.cityName" placeholder="请选择城市" @change="handleCityChange" clearable>
            <el-option v-for="district in cityList" :key="district.cityName" :label="district.cityName" :value="district.cityName" />
          </el-select>
        </el-form-item>
        <el-form-item label="区域" prop="districtName">
          <el-select v-model="form.districtName" placeholder="请选择区域" @change="handleDistrictChange" clearable>
            <el-option v-for="district in districtList" :key="district.districtName" :label="district.districtName" :value="district.districtName" />
          </el-select>
        </el-form-item>
        <el-form-item label="默认预约门店" prop="ishopId">
          <el-select v-model="form.ishopId" placeholder="请选择默认预约门店" clearable>
            <el-option v-for="shop in ishopList" :key="shop.ishopId" :label="shop.name" :value="shop.ishopId" />
          </el-select>
        </el-form-item>
        <el-form-item label="预约类型" prop="shopType">
          <el-select v-model="form.shopType" placeholder="请选择预约类型">
            <el-option v-for="dict in reservation_type" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="随机时间预约" prop="randomMinute">
          <el-select v-model="form.randomMinute" placeholder="请选择随机时间预约">
            <el-option v-for="dict in open_close" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="预约执行分钟" prop="minute">
          <el-input v-model="form.minute" placeholder="请输入预约执行分钟" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="loginIuser()">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <el-dialog :title="tokenTitle" v-model="refreshToken" width="500px" append-to-body>
      <el-form ref="formToken" :model="form">
        <el-form-item label="手机号" prop="mobile">
          <el-input v-model="form.mobile" placeholder="请输入I茅台用户手机号" />
          <div style="margin-top: 10px">
            <el-button type="primary" @click="sendMobileCode(form.mobile)"
              >发送验证码<span v-if="state">({{ stateNum }})</span>
            </el-button>
          </div>
        </el-form-item>

        <el-form-item label="验证码" prop="userId">
          <el-input v-model="form.code" placeholder="请输入验证码" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="refresh(form.mobile, form.code, form.deviceId, 1)">刷新 </el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Iuser">
import { listIuser, getIuser, delIuser, addIuser, updateIuser, sendCode, login, reservation, travelReward, loginIUser } from '@/api/invest/iuser'
import { listIitem } from '@/api/invest/iitem'
import { listIshop, listProvince, listCity, listDistrict } from '@/api/invest/ishop'
// eslint-disable-next-line no-unused-vars
import { require } from '@/utils/require'
const { proxy } = getCurrentInstance()
const { open_close, reservation_type } = proxy.useDict('open_close', 'reservation_type')
const iuserList = ref([])
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref('')
const tokenTitle = ref('')
const openUser = ref(false)
const refreshToken = ref(false)

// 发送短信按钮倒计时
const state = ref(false)
const stateNum = ref(60)

const itemSelect = ref([])
const itemList = ref([])

const provinceList = ref([])
const cityList = ref([])
const districtList = ref([])
const ishopList = ref([])

const operateList = ref([
  { id: 'reservation', icon: 'View', name: '预约', title: '预约', hasPermi: ['invest:iuser:edit'] },
  { id: 'travel', icon: 'View', name: '旅行', title: '旅行', hasPermi: ['invest:iuser:edit'] },
  { id: 'token', icon: 'View', name: '刷新token', title: '刷新token', hasPermi: ['invest:iuser:edit'] },
  { id: 'edit', icon: 'Edit', name: '修改', title: '修改', hasPermi: ['invest:iuser:edit'] },
  { id: 'delete', icon: 'Delete', name: '删除', title: '删除', hasPermi: ['invest:iuser:remove'] }
])
const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    mobile: null,
    token: null,
    cookie: null,
    deviceId: null,
    itemCode: null,
    ishopId: null,
    provinceName: null,
    cityName: null,
    address: null,
    lat: null,
    lng: null,
    minute: null,
    shopType: null,
    randomMinute: null,
    pushPlusToken: null,
    jsonResult: null,
    expireTime: null,
    createUser: null,
    updateUser: null
  },
  queryDistrictParams: {
    pageNum: 1,
    pageSize: 2000,
    provinceName: null,
    cityName: null,
    districtName: null
  },
  queryShopParams: {
    pageNum: 1,
    pageSize: 2000,
    provinceName: null,
    cityName: null,
    districtName: null
  },
  rules: {
    mobile: [{ required: true, message: '手机号不能为空', trigger: 'blur' }],
    userId: [{ required: true, message: '用户id不能为空', trigger: 'blur' }],
    ishopId: [{ required: true, message: '门店id不能为空', trigger: 'blur' }],
    randomMinute: [{ required: true, message: '随机时间预约不能为空', trigger: 'blur' }],
    shopType: [{ required: true, message: '预约类型不能为空', trigger: 'blur' }],
    minute: [{ required: true, message: '预约执行分钟不能为空', trigger: 'blur' }],
    provinceName: [{ required: true, message: '省份不能为空', trigger: 'blur' }],
    cityName: [{ required: true, message: '城市不能为空', trigger: 'blur' }],
    districtName: [{ required: true, message: '区域不能为空', trigger: 'blur' }],
    itemCode: [{ required: true, message: '预约商品不能为空', trigger: 'blur' }]
  },
  addRules: {
    mobile: [{ required: true, message: '手机号不能为空', trigger: 'blur' }],
    ishopId: [{ required: true, message: '默认预约门店不能为空', trigger: 'blur' }],
    code: [{ required: true, message: '验证码不能为空', trigger: 'blur' }],
    randomMinute: [{ required: true, message: '随机时间预约不能为空', trigger: 'blur' }],
    shopType: [{ required: true, message: '预约类型不能为空', trigger: 'blur' }],
    minute: [{ required: true, message: '预约执行分钟不能为空', trigger: 'blur' }],
    provinceName: [{ required: true, message: '省份不能为空', trigger: 'blur' }],
    cityName: [{ required: true, message: '城市不能为空', trigger: 'blur' }],
    districtName: [{ required: true, message: '区域不能为空', trigger: 'blur' }],
    itemCode: [{ required: true, message: '预约商品不能为空', trigger: 'blur' }]
  }
})

const handleOperate = (operate, row) => {
  switch (operate) {
    case 'token':
      handleUpdateToken(row)
      break
    case 'edit':
      handleUpdate(row)
      break
    case 'delete':
      handleDelete(row)
      break
    case 'reservation':
      reservationImaotai(row)
      break
    case 'travel':
      travelRewardImaotai(row)
      break
    default:
      break
  }
}

const { queryParams, queryDistrictParams, queryShopParams, form, rules, addRules } = toRefs(data)

/** 查询省份列表 */
function getProvinceList() {
  listProvince(queryDistrictParams.value).then((response) => {
    provinceList.value = response.rows
  })
}

/** 查询城市列表 */
function getCityList() {
  listCity(queryDistrictParams.value).then((response) => {
    cityList.value = response.rows
  })
}

/** 查询区域列表 */
function getDistrictList() {
  listDistrict(queryDistrictParams.value).then((response) => {
    districtList.value = response.rows
  })
}

/** 查询门店列表 */
function getShopList() {
  listIshop(queryShopParams.value).then((response) => {
    ishopList.value = response.rows
  })
}

/** 查询账号管理列表 */
function getList() {
  listIitem().then((response) => {
    itemList.value = response.rows
  })
  loading.value = true
  listIuser(queryParams.value).then((response) => {
    iuserList.value = response.rows
    total.value = response.total
    loading.value = false
  })
}

//item下拉框选择
function changeItem(e) {
  form.value.itemCode = ''
  itemSelect.value.forEach((e) => {
    form.value.itemCode += e + '@'
  })
}

// 取消按钮
function cancel() {
  open.value = false
  openUser.value = false
  refreshToken.value = false
  reset()
}

// 表单重置
function reset() {
  form.value = {
    mobile: null,
    userId: null,
    token: null,
    cookie: null,
    code: null,
    deviceId: null,
    itemCode: null,
    ishopId: null,
    provinceName: null,
    cityName: null,
    districtName: null,
    address: null,
    lat: null,
    lng: null,
    minute: 8,
    shopType: '1',
    randomMinute: '0',
    pushPlusToken: null,
    jsonResult: null,
    remark: null,
    expireTime: null,
    delFlag: null,
    createTime: null,
    createUser: null,
    updateTime: null,
    updateUser: null,
    createBy: null
  }
  proxy.resetForm('iuserRef')
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm('queryRef')
  handleQuery()
}

// 分页
const handleCurrentChange = (val) => {
  queryParams.value.pageNum = val
  getList()
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map((item) => item.mobile)
  single.value = selection.length !== 1
  multiple.value = !selection.length
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset()
  const _mobile = row.mobile || ids.value
  getIuser(_mobile).then((response) => {
    form.value = response.data
    queryDistrictParams.value.provinceName = form.value.provinceName
    listCity(queryDistrictParams.value).then((response) => {
      cityList.value = response.rows
      queryDistrictParams.value.cityName = form.value.cityName
      listDistrict(queryDistrictParams.value).then((response) => {
        districtList.value = response.rows
        queryShopParams.value.provinceName = form.value.provinceName
        queryShopParams.value.cityName = form.value.cityName
        queryShopParams.value.districtName = form.value.districtName
        listIshop(queryShopParams.value).then((response) => {
          ishopList.value = response.rows
        })
      })
    })
    open.value = true
    itemSelect.value = []
    if (form.value.itemCode.indexOf('@') == -1 && form.value.itemCode !== '') {
      itemSelect.value.push(this.form.itemCode)
    } else {
      const arr = form.value.itemCode.split('@')
      arr.forEach((e) => {
        if (e !== '') {
          itemSelect.value.push(e)
        }
      })
    }
    title.value = '修改账号'
  })
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs.iuserRef.validate((valid) => {
    if (valid) {
      if (form.value.mobile != null) {
        updateIuser(form.value).then((response) => {
          proxy.$modal.msgSuccess('修改成功')
          open.value = false
          getList()
        })
      } else {
        addIuser(form.value).then((response) => {
          proxy.$modal.msgSuccess('新增成功')
          open.value = false
          getList()
        })
      }
    }
  })
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _mobiles = row.mobile || ids.value
  proxy.$modal
    .confirm('是否确认删除选中的数据项？')
    .then(function () {
      return delIuser(_mobiles)
    })
    .then(() => {
      getList()
      proxy.$modal.msgSuccess('删除成功')
    })
    .catch(() => {})
}

//发送验证码
function sendMobileCode(mobile, deviceId) {
  if (deviceId == undefined || deviceId == '') {
    form.value.deviceId = guid()
  } else {
    form.value.deviceId = deviceId
  }
  sendCode(mobile, form.value.deviceId).then((response) => {
    proxy.$modal.msgSuccess('发送成功')
    state.value = true
    const timer = setInterval(() => {
      stateNum.value--
      if (stateNum.value === 0) {
        clearInterval(timer)
        state.value = false
        stateNum.value = 60
      }
    }, 1000)
  })
}
//登录
function loginIuser() {
  proxy.$refs.formIuser.validate((valid) => {
    if (valid) {
      loginIUser(form.value).then((response) => {
        proxy.$modal.msgSuccess('新增成功')
        openUser.value = false
        getList()
      })
    }
  })
}

function refresh(mobile, code, deviceId, status) {
  const msg = status ? '刷新成功' : '登录成功'
  login(mobile, code, deviceId).then((response) => {
    proxy.$modal.msgSuccess(msg)
    open.value = false
    openUser.value = false
    refreshToken.value = false
    getList()
  })
}
function handleUpdateToken(row) {
  refreshToken.value = true
  form.value = {
    mobile: row.mobile,
    deviceId: row.deviceId
  }
  tokenTitle.value = '刷新用户:' + row.remark + '(' + row.mobile + ')登录信息'
}
//预约
function reservationImaotai(row) {
  const mobile = row.mobile || ids.value
  reservation(mobile).then((response) => {
    proxy.$modal.msgSuccess('请求成功，结果看日志')
  })
}
//小茅运旅行活动
function travelRewardImaotai(row) {
  const mobile = row.mobile || ids.value
  travelReward(mobile).then((response) => {
    proxy.$modal.msgSuccess('请求成功，结果看日志')
  })
}
function guid() {
  return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
    const r = (Math.random() * 16) | 0
    const v = c == 'x' ? r : (r & 0x3) | 0x8
    return v.toString(16)
  })
}
function handleAddIUser() {
  reset()
  itemSelect.value = []
  openUser.value = true
}

const handleProvinceChange = (provinceName) => {
  queryDistrictParams.value.provinceName = provinceName
  queryDistrictParams.value.cityName = null
  form.value.cityName = null
  form.value.districtName = null
  form.value.cityName = null
  form.value.ishopId = null
  listCity(queryDistrictParams.value).then((response) => {
    cityList.value = response.rows
    listDistrict(queryDistrictParams.value).then((response) => {
      districtList.value = response.rows
      queryShopParams.value.provinceName = provinceName
      queryShopParams.value.cityName = form.value.cityName
      queryShopParams.value.districtName = form.value.districtName
      listIshop(queryShopParams.value).then((response) => {
        ishopList.value = response.rows
      })
    })
  })
}

const handleCityChange = (cityName) => {
  queryDistrictParams.value.cityName = cityName
  queryDistrictParams.value.districtName = null
  form.value.districtName = null
  form.value.ishopId = null
  listDistrict(queryDistrictParams.value).then((response) => {
    districtList.value = response.rows
    queryShopParams.value.provinceName = form.value.provinceName
    queryShopParams.value.cityName = cityName
    queryShopParams.value.districtName = null
    listIshop(queryShopParams.value).then((response) => {
      ishopList.value = response.rows
    })
  })
}

const handleDistrictChange = (districtName) => {
  queryShopParams.value.districtName = districtName
  queryShopParams.value.cityName = form.value.cityName
  queryShopParams.value.provinceName = form.value.provinceName
  form.value.ishopId = null
  listIshop(queryShopParams.value).then((response) => {
    ishopList.value = response.rows
  })
}
getProvinceList()
getCityList()
getDistrictList()
getShopList()
getList()
</script>
