<template>
  <div class='app-container'>
    <el-form inline>
      <el-form-item label="门店名称或编码：">
        <el-input v-model="data.form.name" placeholder="请输入门店名称或编码" clearable />
      </el-form-item>
      <el-form-item label="门店分组：">
        <el-select v-model="data.form.groupId" placeholder="请选择门店分组" filterable remote :remote-method="groupRemote"
          remote-show-suffix clearable>
          <el-option v-for="item in groupData.options" :key="item.id" :value="item.id" :label="item.name" />
        </el-select>
      </el-form-item>
      <el-form-item label="所属企业：">
        <el-select v-model="data.form.tenantId" placeholder="请选择所属企业" style="width: 200px" filterable remote
          :remote-method="businessRemote" remote-show-suffix clearable>
          <el-option v-for="item in businessData.options" :key="item.id" :value="item.id" :label="item.name" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="getSearch">搜索</el-button>
        <el-button icon="Refresh" @click="getRefresh">重置</el-button>
        <el-button type="primary" plain icon="Plus" @click="getDialog()" v-hasPermi="['store:list:add']">新增</el-button>
      </el-form-item>
    </el-form>
    <!-- 列表 -->
    <div class="table_data">
      <el-descriptions v-for="item in data.tableData" :key="item.id" :column="1">
        <el-descriptions-item>
          {{ item.name }}
        </el-descriptions-item>
        <el-descriptions-item label="门店编码：">
          {{ item.code }}
        </el-descriptions-item>
        <el-descriptions-item>
          <span>{{ item.provinceName }}</span>
          <span v-if="item.cityName"> - {{ item.cityName }}</span>
          <span v-if="item.areaName"> - {{ item.areaName }}</span>
        </el-descriptions-item>
        <el-descriptions-item>
          <el-dropdown class="dropdown" v-hasPermi="['store:list:edit', 'store:list:delete']">
            <el-icon>
              <MoreFilled />
            </el-icon>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item v-if="checkPermi(['store:list:edit'])" @click="getDialog(item.id)">
                  编辑
                </el-dropdown-item>
                <el-dropdown-item v-if="checkPermi(['store:list:delete'])" @click="getDelete(item)">
                  删除
                </el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </el-descriptions-item>
      </el-descriptions>
    </div>
    <pagination v-show="total > 0" :total="total" v-model:page="data.form.pageNum" v-model:limit="data.form.pageSize"
      @pagination="getList" />
    <!-- 弹窗 -->
    <el-dialog v-model="dialogVisible" :title="title" width="500" :before-close="getClose">
      <el-form label-width="100px" :model="data.dialogForm" ref="dialogForm" :rules="data.rules">
        <el-form-item label="门店名称：" prop="name">
          <el-input v-model="data.dialogForm.name" placeholder="请输入门店名称" />
        </el-form-item>
        <el-form-item label="门店编码：" prop="code">
          <el-input v-model="data.dialogForm.code" placeholder="请输入门店编码" />
        </el-form-item>
        <el-form-item label="所属账号：" prop="userId">
          <el-select v-model="data.dialogForm.userId" placeholder="请选择所属账号" filterable remote
            :remote-method="userRemote" remote-show-suffix>
            <el-option v-for="item in userData.options" :key="item.userId" :value="item.userId"
              :label="item.userName" />
          </el-select>
        </el-form-item>
        <el-form-item label="所属企业：" prop="tenantId">
          <el-select v-model="data.dialogForm.tenantId" placeholder="请选择所属企业" filterable remote
            :remote-method="businessRemote" remote-show-suffix>
            <el-option v-for="item in businessData.options" :key="item.id" :value="item.id" :label="item.name" />
          </el-select>
        </el-form-item>
        <el-form-item label="所属城市：" prop="provinceId">
          <el-cascader v-model="data.areaList" :options="areaData.options" placeholder="请选择所属城市"
            :props="{ value: 'id', label: 'name', children: 'childList', expandTrigger: 'hover' }"
            style="width: 100%;" />
        </el-form-item>
        <el-form-item label="门店分组：" prop="groupId">
          <el-select v-model="data.dialogForm.groupId" placeholder="请选择门店分组" filterable remote
            :remote-method="groupRemote" remote-show-suffix>
            <el-option v-for="item in groupData.options" :key="item.id" :value="item.id" :label="item.name" />
            <el-option v-if="data.dialogForm.groupId && !groupData.options.some(i => i.id === data.dialogForm.groupId)"
              :label="data.dialogForm.groupName ? data.dialogForm.groupName : '无'" :value="data.dialogForm.groupId" />
          </el-select>
        </el-form-item>
        <el-form-item label="休眠时间：">
          <div class="time_list" v-for="(item, index) in data.timeList">
            <el-time-picker v-model="data.timeList[index]" is-range format="HH:mm:ss" value-format="HH:mm:ss"
              start-placeholder="开始时间" end-placeholder="结束时间" @change="handleChangeTime($event, index)" />
            <el-link v-show="data.timeList.length > 1" icon="CircleClose" :underline="false"
              @click="handleDeleteDate(index)" />
            <el-link v-show="data.timeList.length - 1 === index" icon="CirclePlus" :underline="false"
              @click="handlePushDate" />
          </div>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="getClose">取消</el-button>
        <el-button type="primary" @click="getSubmit">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { list, detail, remove, submit, edit } from '@/api/store/list'

import { useBusinessSelect, useUserSelect, useGroupSelect, useAreaSelect } from '@/hooks/index'

import { checkPermi } from "@/utils/permission";

const { proxy } = getCurrentInstance()

const { businessData, getBusiness, businessRemote } = useBusinessSelect(true)
getBusiness()
const { userData, getUser, userRemote } = useUserSelect()
getUser()
const { groupData, getGroup, groupRemote } = useGroupSelect()
getGroup()
const { areaData, getArea } = useAreaSelect()
getArea()

// 遮罩层
const loading = ref(false)

const data = reactive({
  // 表单
  form: {
    pageNum: 1,
    pageSize: 10
  },
  // 列表
  tableData: [],
  // 弹窗表单
  dialogForm: {
    timeRestList: []
  },
  // 休眠时间
  timeList: [[]],
  // 地区
  areaList: [],
  // 校验
  rules: {
    name: [{
      required: true, message: '请输入门店名称', trigger: 'blur'
    }],
    code: [{
      required: true, message: '请输入门店编码', trigger: 'blur'
    }],
    userId: [{
      required: true, message: '请选择所属账号', trigger: 'change'
    }],
    tenantId: [{
      required: true, message: '请选择所属企业', trigger: 'change'
    }],
    provinceId: [{
      required: true, message: '请选择所属城市', trigger: 'blur'
    }],
    groupId: [{
      required: true, message: '请选择门店分组', trigger: 'change'
    }]
  }
})

// 总数据
const total = ref(0)

// 列表
const getList = () => {
  loading.value = true
  list(data.form).then(res => {
    if (res.code === 0) {
      data.tableData = res.data
      total.value = res.total
      loading.value = false
    }
  })
}
getList()

// 搜索
const getSearch = () => {
  data.form.pageNum = 1
  getList()
}

// 重置
const getRefresh = () => {
  data.form = {
    pageNum: 1,
    pageSize: 10
  }
  getList()
}

// 弹窗
const dialogVisible = ref(false)
// 弹窗标题
const title = ref('')
// 打开弹窗
function getDialog(id) {
  dialogVisible.value = true
  title.value = '新增'
  if (id) {
    getDetail(id)
  }
}

// 详情
const getDetail = (id) => {
  title.value = '编辑'
  detail({ id: id }).then(res => {
    if (res.code === 0) {
      data.dialogForm = res.data
      data.areaList = [res.data.provinceId, res.data.cityId, res.data.areaId]
      if (res.data.timeRestList.length < 1) {
        data.timeList = [[]]
      } else {
        data.timeList = []
      }
      res.data.timeRestList.map(i => {
        data.timeList.push([i.startTime, i.endTime])
      })
    }
  })
}

// 增加时间
const handlePushDate = () => {
  let boolean = false
  data.timeList.map(i => boolean = i.length === 0 ? true : false)
  if (boolean) {
    proxy.$modal.msgError('有时间段未填')
  } else {
    data.timeList.push([])
  }
}

// 删除时间
const handleDeleteDate = (index) => {
  data.timeList.splice(index, 1)
}

const handleChangeTime = (e, index) => {
  if (e !== null) {
    data.dialogForm.timeRestList = []
    const start = proxy.hoursToSeconds(e[0])
    const end = proxy.hoursToSeconds(e[1])
    for (let i = 0; i < data.timeList.length; i++) {
      if (i !== index) {
        let st = proxy.hoursToSeconds(data.timeList[i][0])
        let en = proxy.hoursToSeconds(data.timeList[i][1])
        if (start >= st && start <= en || end >= st && end <= en || start <= st && end >= en) {
          data.timeList.splice(index, 1)
          proxy.$modal.msgError("该时间段已设置！")
          return false
        }
      }
      data.dialogForm.timeRestList.push({
        startTime: data.timeList[i][0],
        endTime: data.timeList[i][1]
      })
    }
  } else {
    data.dialogForm.timeRestList.splice(index, 1)
  }
}

// 删除
const getDelete = (row) => {
  proxy.$modal.confirm(`是否删除门店名称为：${row.name}的数据?`).then(() => {
    remove({ id: row.id }).then(res => {
      if (res.code === 0) {
        proxy.$modal.msgSuccess('删除成功！')
        getList()
      }
    })
  })
}

// 提交
const getSubmit = () => {
  proxy.$refs.dialogForm.validate(valid => {
    if (valid) {
      if (data.dialogForm.id) {
        edit(data.dialogForm).then(res => {
          if (res.code === 0) {
            proxy.$modal.msgSuccess('编辑成功！')
            getClose()
            getList()
          }
        })
      } else {
        submit(data.dialogForm).then(res => {
          if (res.code === 0) {
            proxy.$modal.msgSuccess('新增成功！')
            getClose()
            getList()
          }
        })
      }
    } else {
      return false
    }
  })
}

// 取消
const getClose = () => {
  dialogVisible.value = false
  data.dialogForm = {}
  data.timeList = [[]]
  data.areaList = []
  proxy.$refs.dialogForm.resetFields()
}

watch(() => data.areaList, (val) => {
  if (val) {
    data.dialogForm.provinceId = val[0]
    data.dialogForm.cityId = val[1]
    data.dialogForm.areaId = val[2]
  }
})
</script>

<style lang="scss" scoped>
.time_list {
  display: flex;
  align-items: center;
  width: 100%;
  margin-top: 18px;

  .el-link {
    margin-left: 10px;
    font-size: 16px;
  }
}

.time_list:first-child {
  margin: 0;
}

.table_data {
  display: flex;
  flex-wrap: wrap;
}

.el-descriptions {
  width: 300px;
  padding: 20px 20px 0;
  border: 1px solid #e5e5e5;
  margin: 0 60px 20px 0;
  display: flex;
  border-left-color: #2c65ff;
  border-left-width: 4px;
  position: relative;
}

.dropdown {
  position: absolute;
  top: 10px;
  right: 10px;
}
</style>