<template>
    <div class="app-container">
        <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
            <!-- <el-form-item label="所属企业ID" prop="companyId">
        <el-input v-model="queryParams.companyId" placeholder="请输入所属企业ID" clearable @keyup.enter="handleQuery" />
      </el-form-item>-->
            <!-- <el-form-item label="应用模板ID" prop="appId">
        <el-input
          v-model="queryParams.appId"
          placeholder="请输入应用模板ID"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>-->
            <!-- <el-form-item label="应用名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入应用名称"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>-->
            <!-- <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>-->
        </el-form>

        <el-row :gutter="10" class="mb8">
            <el-col :span="1.5">
                <el-button type="primary" plain icon="Plus" @click="handlechoose">选择展厅</el-button>
            </el-col>
            <!-- <el-col :span="1.5">
        <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate"
          >修改</el-button>
      </el-col>-->
            <!-- <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['VRdemo:selectApp:add']"
        >新增</el-button>
      </el-col>-->
            <!-- <el-col :span="1.5">
        <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['VRdemo:selectApp:remove']">删除</el-button>
      </el-col>-->
            <!-- <el-col :span="1.5">
        <el-button type="warning" plain icon="Download" @click="handleExport"
          v-hasPermi="['VRdemo:selectApp:export']">导出</el-button>
      </el-col>-->
            <!-- <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar> -->
        </el-row>

        <el-table v-loading="loading" :data="selectAppList" @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="55" align="center" />
            <el-table-column label="展厅编号" align="center" prop="companyAppId" />
            <!-- <el-table-column label="所属企业" align="center" prop="companyId" /> -->
            <!-- <el-table-column label="应用模板ID" align="center" prop="appId" /> -->
            <el-table-column label="展厅名称" align="center" prop="name" />
            <el-table-column label="展厅图标" align="center" prop="logo" width="100">
                <template #default="scope">
                    <QImgPreview :src="scope.row.logo" :width="50" :height="50" />
                </template>
            </el-table-column>
            <el-table-column label="展厅封面图" align="center" prop="cover" width="100">
                <template #default="scope">
                    <QImgPreview :src="scope.row.cover" :width="50" :height="50" />
                </template>
            </el-table-column>
            <!-- <el-table-column label="应用设置信息" align="center" prop="setting" />
      <el-table-column label="创建者" align="center" prop="createBy" />-->
            <el-table-column label="创建时间" align="center" prop="createTime" width="180">
                <template #default="scope">
                    <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d}') }}</span>
                </template>
            </el-table-column>
            <!-- <el-table-column label="更新者" align="center" prop="updateBy" /> -->
            <el-table-column label="更新时间" align="center" prop="updateTime" width="180">
                <template #default="scope">
                    <span>{{ parseTime(scope.row.updateTime, '{y}-{m}-{d}') }}</span>
                </template>
            </el-table-column>
            <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
                <template #default="scope">
                    <el-button link type="primary" icon="Edit" @click="EnterCompanyApp(scope.row)">选定</el-button>
                    <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)">修改</el-button>
                    <el-button link type="primary" icon="View" @click="goTarget(scope.row)">预览</el-button>
                    <!-- <el-button link type="primary" @click="handleDelete(scope.row)"
          >删除</el-button>-->
                </template>
            </el-table-column>
        </el-table>

        <pagination
            v-show="total > 0"
            :total="total"
            v-model:page="queryParams.pageNum"
            v-model:limit="queryParams.pageSize"
            @pagination="getList"
        />

        <!-- 添加或修改展厅页面对话框 -->
        <el-dialog :title="title" v-model="open" width="500px" append-to-body>
            <el-form ref="selectAppRef" :model="form" :rules="rules" label-width="80px">
                <!-- <el-form-item label="所属企业" prop="companyId">
          <el-input v-model="form.companyId" placeholder="请输入所属企业ID" />
        </el-form-item>-->
                <!-- <el-form-item label="应用模板ID" prop="appId">
          <el-input v-model="form.appId" placeholder="请输入应用模板ID" />
        </el-form-item>-->
                <el-form-item label="展厅名称" prop="name">
                    <el-input v-model="form.name" placeholder="请输入展厅名称" />
                </el-form-item>
                <el-form-item label="展厅图标" prop="logo">
                    <QImgUpload v-model="form.logo" :imagedataids="imagedataIds" />
                </el-form-item>
                <el-form-item label="应用封面图" prop="cover">
                    <QImgUpload v-model="form.cover" />
                </el-form-item>
            </el-form>
            <template #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="openDialog" width="700px" append-to-body>
            <el-table
                :data="chooseList"
                border
                height="250"
                style="width: 100%"
                highlight-current-row
                @current-change="handleCurrentChange"
                row-key="index"
            >
                <el-table-column type="index" label="序号" width="180" align="center" />
                <el-table-column prop="title" label="标题" width="240" align="center" />
                <el-table-column prop="price" label="单价" width="240" align="center" />
            </el-table>
            <el-divider />
            <el-form label-width="100px" label-position="left">
                <el-form-item label="展厅名称">
                    <el-input v-model="returnName" placeholder="请输入展厅名称" />
                </el-form-item>
                <el-form-item label="展厅logo">
                    <QImgUpload v-model="returnLogo" />
                </el-form-item>
                <el-form-item label="展厅封面图">
                    <QImgUpload v-model="returnCover" />
                </el-form-item>
            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <el-button type="primary" @click="submitChoose">确 定</el-button>
                    <el-button @click="cancelDialog">取 消</el-button>
                </div>
            </template>
        </el-dialog>
    </div>
</template>

<script setup name="SelectApp">
import {
    enterApp,
    listSelectApp,
    getSelectApp,
    delSelectApp,
    addSelectApp,
    updateSelectApp,
    chooseAppList,
    addCompanyApp
} from '@/api/VRdemo/selectApp'
import { ref } from 'vue'
import { useRouter } from 'vue-router'
// import Cookies from 'js-cookie'
// import cnchar from 'cnchar'

const router = useRouter()

const { proxy } = getCurrentInstance()

const selectAppList = ref([])
const chooseList = ref([])
const open = ref(false)
const openDialog = 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 companyApp = ref()
const returnAppId = ref()
const returnName = ref()
const returnLogo = ref()
const returnCover = ref()
const currentRow = ref()
const appCookie = ref('')
const imagedataIds = ref('')
const data = reactive({
    form: {},
    queryParams: {
        pageNum: 1,
        pageSize: 10,
        companyId: null,
        appId: null,
        name: null,
        logo: null,
        cover: null,
        setting: null
    },
    rules: {
        // companyId: [
        //   { required: true, message: "所属企业不能为空", trigger: "blur" }
        // ],
        // appId: [
        //   { required: true, message: "应用模板ID不能为空", trigger: "blur" }
        // ],
        name: [{ required: true, message: '展厅名称不能为空', trigger: 'blur' }],
        logo: [{ required: true, message: '展厅图标不能为空', trigger: 'blur' }]
        // cover: [
        //   { required: true, message: "应用封面图不能为空", trigger: "blur" }
        // ],
        // setting: [
        //   { required: true, message: "应用设置信息不能为空", trigger: "blur" }
        // ],
    }
})

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

/** 查询选择页面列表 */
function getList() {
    loading.value = true
    listSelectApp(queryParams.value).then(response => {
        selectAppList.value = response.rows
        total.value = response.total
        //部署到nginx时可以显示图片
        // for (let i = 0; i < total.value; i++) {
        //   if (selectAppList.value[i].logo != null) {
        //     selectAppList.value[i].logo =
        //       import.meta.env.VITE_STATIC_BASE_URL + selectAppList.value[i].logo;
        //   }
        // }
        // for (let x = 0; x < total.value; x++) {
        //   if (selectAppList.value[x].cover != null) {
        //     selectAppList.value[x].cover =
        //       import.meta.env.VITE_STATIC_BASE_URL + selectAppList.value[x].cover;
        //   }
        // }
        loading.value = false
    })
}

/** 获取可选择的展厅列表 */
function getChooseList() {
    chooseAppList().then(response => {
        let i = 0
        chooseList.value = []
        for (let i = 0; i < response.appList.length; i++) {
            chooseList.value[i] = response.appList[i]
        }
    })
}

const handleCurrentChange = val => {
    currentRow.value = val
    returnAppId.value = currentRow.value.appId
}

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

// 取消选择展厅弹窗按钮
function cancelDialog() {
    openDialog.value = false
    returnAppId.value = null
    returnName.value = null
    returnLogo.value = null
    returnCover.value = null
    currentRow.value = null
}

// 表单重置
function reset() {
    form.value = {
        companyAppId: null,
        companyId: null,
        appId: null,
        name: null,
        logo: null,
        cover: null,
        setting: [],
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null
    }
    proxy.resetForm('selectAppRef')
}

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

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

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

/** 新增按钮操作 */
function handleAdd() {
    reset()
    open.value = true
    title.value = '添加选择页面'
}

/** 修改按钮操作 */
function handleUpdate(row) {
    reset()
    const _companyAppIds = row.companyAppId || ids.value
    getSelectApp(_companyAppIds).then(response => {
        form.value = response.data
        open.value = true
        imagedataIds.value = response.data.companyAppId
        title.value = '修改展厅页面'
    })
}

/** 选择展厅按钮操作 */
function handlechoose() {
    getChooseList()
    openDialog.value = true
}

/** 选定按钮操作 ***************************/
function EnterCompanyApp(row) {
    const _companyAppIds = row.companyAppId || ids.value
    proxy.$modal
        .confirm('是否启用"' + row.name + '"的展厅？')
        .then(function () {
            // //cookie中储存展厅编号，企业id，展厅名称
            // appCookie.value = row.companyAppId + "," + row.companyId + "," + row.name;
            //判断cookie是否存在
            // const getcookie = Cookies.get("appCookie");
            // if (getcookie != null) {
            //   Cookies.remove("appCookie");
            // }
            // let seconds = 10;// 10 秒后失效
            // let expires = new Date(new Date() * 1 + seconds * 1000);
            // //写入cookies
            // Cookies.set("appCookie", appCookie.value, { expires: expires });
            return enterApp(_companyAppIds).then(response => {
                companyApp.value = response.data.name
            })
        })
        .then(() => {
            proxy.$modal.msgSuccess('启用成功！')
        })
        .catch(() => {})
}

/** 提交按钮 */
function submitForm() {
    proxy.$refs['selectAppRef'].validate(valid => {
        if (valid) {
            // form.value.setting = form.value.setting.join(",");
            if (form.value.companyAppId != null) {
                updateSelectApp(form.value).then(response => {
                    proxy.$modal.msgSuccess('修改成功')
                    open.value = false
                    getList()
                })
            } else {
                addSelectApp(form.value).then(response => {
                    proxy.$modal.msgSuccess('新增成功')
                    open.value = false
                    getList()
                })
            }
        }
    })
}

/** 提交选择展厅 */
function submitChoose() {
    addCompanyApp({
        appId: returnAppId.value,
        name: returnName.value,
        logo: returnLogo.value,
        cover: returnCover.value
    }).then(response => {
        openDialog.value = false
        returnAppId.value = null
        returnName.value = null
        returnLogo.value = null
        returnCover.value = null
        currentRow.value = null
        getList()
    })
}

/** 删除按钮操作 */
function handleDelete(row) {
    const _companyAppIds = row.companyAppId || ids.value
    proxy.$modal
        .confirm('是否确认删除选择页面编号为"' + _companyAppIds + '"的数据项？')
        .then(function () {
            return delSelectApp(_companyAppIds)
        })
        .then(() => {
            getList()
            proxy.$modal.msgSuccess('删除成功')
        })
        .catch(() => {})
}

/** 导出按钮操作 */
function handleExport() {
    proxy.download(
        'VRdemo/selectApp/export',
        {
            ...queryParams.value
        },
        `selectApp_${new Date().getTime()}.xlsx`
    )
}
/** 打开预览窗口 */
function goTarget(row) {
    //使用展厅名笔画数加上展厅id的和转成16进制获得加密的cid
    // let strokes = row.name.stroke()//获取笔画数
    let strokes = row.name.length
    let sum = row.companyAppId + strokes
    let id = sum.toString(16)
    let url = 'http://124.71.57.20:3751/cid=' + id + '/name=' + row.name
    window.open(url, '__blank')
}
getList()
</script>
