<template>
  <el-drawer :model-value="visible" :title="store._id ? '编辑店铺' : '新增店铺'" size="80%" :close-on-click-modal="false"
    style="--el-drawer-padding-primary: 0" @close="close()">
    <my-layout v-loading="loading" class="bg-[#f2f3f4]">
      <layout-main ref="mainRef">
        <el-form class="bg-white p-15px overflow-hidden" label-suffix="：" label-width="100" size="large">
          <el-row :gutter="10">
            <el-col :span="24">
              <div active-title-bar class="mb-10px">店铺基本信息</div>
            </el-col>
            <el-col :span="12">
              <el-form-item class="is-required" label="店铺名称">
                <el-input v-model="store.name" placeholder="请输入店铺名称" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item class="is-required" label="店铺ID">
                <el-input v-model="store.store_id" placeholder="请输入店铺ID" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item class="is-required" label="店铺类型">
                <el-select v-model="store.type" class="w-full" placeholder="请选择店铺类型">
                  <el-option v-for="i in storeType" :label="i" :key="i" :value="i" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="关联账号">
                <el-select v-model="store.accountId" class="w-full" placeholder="请选择关联账号" filterable clearable>
                  <el-option v-for="i in accountList" :label="i.label" :key="i.value" :value="i.value" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="店铺介绍">
                <el-input v-model="store.introduce" type="textarea" resize="none" :autosize="{ minRows: 4, maxRows: 8 }"
                  placeholder="请输入店铺介绍" maxlength="300" show-word-limit />
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="店铺图片">
                <div v-if="store.imgs" class="flex-grow flex flex-wrap">
                  <div class="w-80px h-80px mr-15px mb-10px relative" v-for="(i, index) in store.imgs"
                    v-loading="i.uid && uploadStatus[i.uid] === 'loading'" :key="index">
                    <el-image :src="i.url ? i.url : i" fit="cover" class="w-full h-full rounded"
                      :preview-src-list="previewImages" :initial-index="index" />
                    <div v-if="i.uid && uploadStatus[i.uid] === 'error'"
                      class="text-12px text-red-500 text-center absolute w-full top-30px leading-20px h-20px bg-gray-300 bg-opacity-80">
                      上传失败</div>
                    <div class="absolute -top-10px -right-10px w-20px h-20px cursor-pointer"
                      @click.stop="removeImg(index)">
                      <el-icon class="text-20px text-red-500">
                        <CircleCloseFilled />
                      </el-icon>
                    </div>
                  </div>
                  <el-upload v-if="store.imgs && store.imgs.length < 5" multiple ref="uploadRef" accept="image/*"
                    action="#" :show-file-list="false" list-type="picture" :limit="5 - store.imgs.length"
                    :auto-upload="false" @change="changeFile">
                    <template #trigger>
                      <div
                        class="flex items-center justify-center w-80px h-80px border-1 border-dashed text-blue-500 border-blue-500 rounded">
                        <el-icon>
                          <CameraFilled />
                        </el-icon>
                      </div>
                    </template>
                  </el-upload>
                </div>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <div active-title-bar class="mb-10px">店铺地理信息</div>
            </el-col>
            <el-col v-if="store.region" :span="24">
              <el-form-item class="is-required" label="省市区">
                <el-row class="flex-grow overflow-hidden" :gutter="10">
                  <el-col :span="8">
                    <el-select v-model="store.region[0]" filterable class="w-full" placeholder="请选择省"
                      @change="changeProvince">
                      <el-option v-for="i in region" :key="i.value" :label="i.label" :value="i.value" />
                    </el-select>
                  </el-col>
                  <el-col :span="8">
                    <el-select v-model="store.region[1]" filterable class="w-full" placeholder="请选择市"
                      @change="changeCity">
                      <el-option v-for="i in cityList" :key="i.value" :label="i.label" :value="i.value" />
                    </el-select>
                  </el-col>
                  <el-col :span="8">
                    <el-select v-model="store.region[2]" filterable class="w-full" placeholder="请选择区">
                      <el-option v-for="i in districtList" :key="i.value" :label="i.label" :value="i.value" />
                    </el-select>
                  </el-col>
                </el-row>
              </el-form-item>
              <el-col :span="24">
                <el-form-item label="详情地址">
                  <el-input v-model="store.address" placeholder="请输入详情地址" />
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="坐标">
                  <el-input v-model="store.longitude" class="w-200px" placeholder="请输入经度">
                    <template #prepend>经度</template>
                  </el-input>
                  <el-input v-model="store.latitude" class="w-200px ml-10px" placeholder="请输入纬度">
                    <template #prepend>纬度</template>
                  </el-input>
                </el-form-item>
              </el-col>
            </el-col>
            <el-col :span="24">
              <div active-title-bar class="mb-10px">店铺经营信息</div>
            </el-col>
            <el-col :span="12">
              <el-form-item class="is-required" label-width="140" label-position="left" label="互联网诊查费">
                <el-select v-model="store.charge_id" class="w-full" placeholder="请选择互联网诊查费">
                  <el-option v-for="i in chargeList" :label="i.label" :key="i.value" :value="i.value" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label-width="140" label-position="left" label="中药饮片配方资质">
                <el-select v-model="store.saleWine" class="w-full" placeholder="请选择是否有中药饮片配方资质">
                  <el-option label="有" :value="true" />
                  <el-option label="无" :value="false" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item class="is-required" label="店铺状态">
                <template #label>
                  <el-tooltip effect="light" content="店铺停用后，所有店铺关联人员账号无法使用" placement="top">
                    <div class="flex items-center">
                      <span>店铺状态</span>
                      <el-icon class="text-gray-500">
                        <QuestionFilled />
                      </el-icon>
                    </div>
                  </el-tooltip>
                </template>
                <el-radio-group v-model="store.status">
                  <el-radio v-for="i in storeStatus" :label="i" :value="i">{{ i }}</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="营业时间">
                <el-input v-model="store.openingHours" placeholder="请输入营业时间" />
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </layout-main>
      <layout-item>
        <div common-shadow--r class="py-12px bg-white text-center relative z-1">
          <el-button plain class="w-100px" @click="close()">取消</el-button>
          <el-button type="primary" class="w-100px" @click="confirm()">确认</el-button>
        </div>
      </layout-item>
    </my-layout>
  </el-drawer>
</template>
<script setup>
import { computed, nextTick, ref, watch } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import dayjs from 'dayjs';
import { addDrugStore, editDrugStore, getChargeItemList } from '@/api/hlw'
import { updateFile } from "@/api/uploadFIle.js";
import region from '@/baseData/region.js';
import { storeStatus, storeType, DrugStore } from './dict.js'
import { getAccountOptions } from '@/api/account';

import { CameraFilled } from "@element-plus/icons-vue";
import MyLayout, { LayoutMain, LayoutItem } from "@/components/layout";

const props = defineProps({
  data: {
    type: Object,
    default: () => ({})
  },
  visible: {
    type: Boolean,
    default: false,
  },
});

const emit = defineEmits(["close", 'change']);
const mainRef = ref(null);
const store = ref({})
const chargeList = ref([]);
const loading = ref(false);
const uploadRef = ref()
const uploadStatus = ref({})
const accountList = ref([]);

const previewImages = computed(() => {
  return store.value && Array.isArray(store.value.imgs) ? store.value.imgs.map(i => i.url).filter(Boolean) : []
})
const province = computed(() => {
  const province = store.value.region && store.value.region[0] ? store.value.region[0] : '';
  return region.find(item => item.value === province) || {}
})
const cityList = computed(() => Array.isArray(province.value.children) ? province.value.children : []);
const city = computed(() => {
  const city = store.value.region && store.value.region[1] ? store.value.region[1] : '';
  return cityList.value.find(item => item.value === city) || {}
})
const districtList = computed(() => Array.isArray(city.value.children) ? city.value.children : []);

function changeProvince() {
  store.value.region[1] = '';
  store.value.region[2] = '';
}

function changeCity() {
  store.value.region[2] = '';
}

function changeFile({ raw: file, url, uid }) {
  if (store.value.imgs.length < 5) {
    store.value.imgs.push({ file, url, uid });
  }
  uploadRef.value && uploadRef.value.clearFiles();
}

function close() {
  emit("close");
}

function removeImg(index) {
  ElMessageBox.confirm('确定要删除该图片吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    store.value.imgs.splice(index, 1);
  }).catch(() => { })
}

async function confirm() {
  if (loading.value) return;
  if (store.value.name.trim() === '') {
    ElMessage.info('请输入店铺名称')
    return
  }
  if (store.value.store_id.trim() === '') {
    ElMessage.info('请输入店铺ID')
    return
  }
  if (!storeType.includes(store.value.type)) {
    ElMessage.info('请选择店铺类型')
    return
  }
  if (!region.some(i => i.value === store.value.region[0])) {
    ElMessage.info('请选择省份')
    return
  }
  if (!cityList.value.some(i => i.value === store.value.region[1])) {
    ElMessage.info('请选择城市')
    return
  }
  if (!districtList.value.some(i => i.value === store.value.region[2])) {
    ElMessage.info('请选择区县')
    return
  }
  if (!chargeList.value.some(i => i.value === store.value.charge_id)) {
    ElMessage.info('请选择互联网诊查费')
    return
  }
  if (!storeStatus.includes(store.value.status)) {
    ElMessage.info('请选择店铺状态')
    return
  }
  loading.value = true;
  const res = await uploadImgs();
  if (!res) {
    loading.value = false;
    ElMessage.error('图片上传失败')
    return
  }
  const params = { ...store.value };
  const { success, message } = await (props.data._id ? editDrugStore({ id: props.data._id, params }) : addDrugStore({ params }));
  loading.value = false;
  if (success) {
    ElMessage.success(message);
    close()
    emit('change');
  } else {
    ElMessage.error(message);
  }
}

async function getCharges() {
  const { success, data } = await getChargeItemList();
  chargeList.value = data && Array.isArray(data.list) ? data.list.map(i => ({
    label: `${i.fee}元`,
    value: i.code
  })) : [];
  if (!success) {
    ElMessage.error('获取互联网诊查费失败')
  }
}

async function getAccountList() {
  const { data, success, message } = await getAccountOptions();
  accountList.value = data && Array.isArray(data.list) ? data.list.map(i => ({
    label: i.anotherName,
    value: i._id
  })) : []
  if (!success) {
    ElMessage.error(message);
  }
}

async function uploadImgs() {
  uploadStatus.value = {};
  const files = store.value.imgs.filter(i => i.file);
  if (files.length) {
    const res = await Promise.all(files.map(i => upload(i)));
    return res.every(i => i)
  }
  return true

}

async function upload({ file, url, uid }) {
  uploadStatus.value[uid] = 'loading';
  try {
    const res = await updateFile(`${+new Date()}_${Math.ceil(Math.random() * 10000)}_${file.name}`, file);
    if (res && res.download_url) {
      const index = store.value.imgs.findIndex(i => i.uid === uid);
      store.value.imgs[index] = res.download_url;
      uploadStatus.value[uid] = 'success';
      return true
    }
  } catch (e) {
    uploadStatus.value[uid] = 'error';
  }
  return false
}

watch(() => props.visible, async n => {
  if (n) {
    getAccountList()
    if (chargeList.value.length === 0) {
      getCharges()
    }
    const _store = new DrugStore();
    store.value = props.data._id ? _store.init(props.data, false) : _store.init();
    nextTick().then(() => mainRef.value && mainRef.value.scrollTo(0))
  }
})
</script>
<style lang="scss" scoped></style>
