<template>
  <div style="padding: 8px">
    <el-card shadow="never" style="border-radius: 6px">
      <el-form :inline="true" :model="queryForm" class="demo-form-inline">
        <el-form-item label="场景名称">
          <el-input v-model="queryForm.achieveName" placeholder="场景名称"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="queryScenes">查询</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <el-card shadow="never" style="border-radius: 6px;margin-top: 12px">
      <el-button type="primary" @click="addSceneBtnClick">新增</el-button>
      <el-table
        v-loading="load"
        :data="sceneList"
        style="width: 100%"
      >
        <el-table-column
          v-if="false"
          prop="achieveId">
        </el-table-column>
        <el-table-column
          prop="achieveName"
          label="名称">
        </el-table-column>
        <!--        <el-table-column-->
        <!--            prop="templateName"-->
        <!--            label="使用模版">-->
        <!--        </el-table-column>-->
        <!--        <el-table-column-->
        <!--            label="缩略图">-->
        <!--          <template slot-scope="scope">-->
        <!--            <div class="miniLayout">-->
        <!--              <component :is="JSON.parse(scope.row.achieveContent).center"-->
        <!--                         :tree="JSON.parse(scope.row.achieveContent).centerChildren"></component>-->
        <!--            </div>-->
        <!--          </template>-->
        <!--        </el-table-column>-->
        <el-table-column
          fixed="right"
          label="操作"
          width="300">
          <template #default="scope">
            <el-button @click="viewDetails(scope.row)" type="text" size="small" style="padding: 0 4px">全屏查看
            </el-button>
            <el-button @click="querySceneInfo(scope.row)" type="text" size="small" style="padding: 0 4px">修改模版
            </el-button>
            <el-button @click="bindComponents(scope.row)" type="text" size="small" style="padding: 0 4px">绑定组件
            </el-button>
            <el-popconfirm
              title="确定删除吗？"
              @confirm="delSceneOk(scope.row.achieveId)">
              <template #reference>
                <el-button type="text" size="small" style="padding: 0 4px">删除</el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
      <div style="margin-top: 12px">
        <pagination v-show="total > 0" v-model:page="queryForm.pageNum" v-model:limit="queryForm.pageSize"
                    :total="total" @pagination="getList" />
      </div>
    </el-card>

    <el-dialog
      :title="sceneDialogTitle"
      v-model="addSceneDialogVisible"
      width="30%">
      <el-form ref="form" :model="sceneForm" label-width="80px">
        <el-form-item label="场景名称">
          <el-input v-model="sceneForm.achieveName"></el-input>
        </el-form-item>
        <el-form-item label="使用模版">
          <div @click="selectModel">
            <div class="useModel" v-if="!sceneForm.achieveContent.center">
              <i class="el-icon-plus"></i>
            </div>
            <div class="layout" ref="layout" v-if="sceneForm.achieveContent.center"
                 :style="`background-image:url(${(sceneForm.achieveContent.pageCfg||{}).bg})`">
              <component style="pointer-events: none" :is="components[sceneForm.achieveContent.center]"
                         :tree="sceneForm.achieveContent.centerChildren"></component>
            </div>
          </div>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="addSceneDialogVisible = false">取 消</el-button>
          <el-button type="primary" v-if="sceneDialogTitle === '添加场景'" @click="addSceneOk">确 定</el-button>
          <el-button type="primary" v-if="sceneDialogTitle === '修改场景'" @click="upDateSceneOk">确 定</el-button>
        </div>
      </template>
    </el-dialog>

    <el-dialog
      title="选择模版"
      append-to-body
      v-model="selectModelDialogVisible"
      width="700px">

      <div class="modelListItem" v-for="i in modelList" @click="useModel(i)">
        <div class="modelListItemContent"
             :style="`background-image:url(${(JSON.parse(i.templateContent).pageCfg||{}).bg || ''})`">

          <component style="pointer-events: none;"
                     v-if="JSON.parse(i.templateContent).center"
                     :is="components[JSON.parse(i.templateContent).center]"
                     :tree="JSON.parse(i.templateContent).centerChildren"></component>
        </div>
        <div class="modelListItemName">
          {{ i.templateName || ' &nbsp; ' }}
        </div>
      </div>
      <div class="modelListItem" @click="useModel({templateContent:'{}'})">
        <div class="blankModel">
        </div>
        <div class="modelListItemName">
          空白模版
        </div>
      </div>

      <pagination v-show="total1 > 0" v-model:page="modelPagination.pageNum" v-model:limit="modelPagination.pageSize"
                  :total="total1" @pagination="getModelList" />

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="selectModelDialogVisible = false">关 闭</el-button>
        </div>
      </template>
    </el-dialog>

    <el-dialog
      v-model="bindComponentsDialogVisible"
      fullscreen
      width="600px">
      <template #header="{ close, titleId, titleClass }">
        <div>
        <span>
        绑定组件
        </span>
          <el-button @click="toPageCfg">页面配置</el-button>
        </div>
      </template>
      <div class="bindComponents" ref="container">
        <div ref="scene" class="scene"
             :style="`width:${pageData.width?( pageData.width+'px'):'100%'};height:${pageData.height?( pageData.height+'px'):'100%'};background-image:url(${pageCfg.bg})`">
          <component :is="components[bindComponentsData.sceneData.center]"
                     :styleData="pageCfg.styleData"
                     :tree="bindComponentsData.sceneData.centerChildren"></component>
<!--          {{ bindComponentsData.sceneData.center}}-->
        </div>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="bindComponentsDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="bindComponentsOk">确 定</el-button>
        </div>
      </template>
    </el-dialog>

    <el-dialog title="页面配置" v-model="pageCfgDialogVisible" width="900px">
      <el-form :model="pageCfg">
        <el-form-item label="页面类型" label-width="120px">
          <el-radio-group v-model="pageCfg.sizeType">
            <el-radio :label="1">固定宽高</el-radio>
            <el-radio :label="2">固定比例</el-radio>
            <el-radio :label="3">撑满容器</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="页面大小" label-width="120px" v-if="pageCfg.sizeType">
          <el-col :span="2" style="text-align: center">长度</el-col>
          <el-col :span="4">
            <el-input v-model="pageCfg.width"></el-input>
          </el-col>
          <el-col style="text-align: center" :span="2">宽度</el-col>
          <el-col :span="4">
            <el-input v-model="pageCfg.height"></el-input>
          </el-col>
        </el-form-item>
        <el-form-item label="画布背景" label-width="120px">
          <el-upload
            class="avatar-uploader"
            action="dev-api/basic/hwTemplateAchieve/saveImage"
            :headers="{
            authorization:'Bearer ' + getToken()
              }"
            :show-file-list="false"
            :on-success="getImg">
            <img v-if="pageCfg.bg" :src="pageCfg.bg" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>

      </el-form>
      <el-form ref="form" :model="pageCfg.styleData" label-width="120px">
        <el-form-item label="选择风格">
          <el-select v-model="pageCfg.styleData.region" placeholder="请选择风格">
            <el-option label="风格一" value="style1"></el-option>
            <el-option label="风格二" value="style2"></el-option>
            <el-option label="风格三" value="style3"></el-option>
            <el-option label="自定义" value="custom"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="基准颜色">
          <el-tag
            :key="tag"
            v-for="(tag,k) in pageCfg.styleData.colors"
            closable
            :disable-transitions="false"
            @close="colorsClose(tag)">
            <el-color-picker show-alpha v-model="colors[k]" size="mini"
                             @change="colorsChange($event,k)"></el-color-picker>
          </el-tag>
          <el-color-picker show-alpha
                           class="input-new-tag"
                           v-if="inputVisible"
                           v-model="inputValue"
                           ref="saveTagInputRef"
                           size="small"
                           @change="colorsInputConfirm"></el-color-picker>
          <el-button v-else class="button-new-tag" size="small" @click="showInput">添加颜色</el-button>
        </el-form-item>

        <el-form-item label="颜色库">
          <el-tag
            :key="tag"
            v-for="(tag,k) in (pageCfg.styleData||{}).colors1"
            closable
            :disable-transitions="false"
            @close="colorsClose1(tag)">
            <el-color-picker show-alpha v-model="colors1[k]" size="mini"
                             @change="colorsChange1($event,k)"></el-color-picker>
          </el-tag>
          <el-color-picker show-alpha
                           class="input-new-tag"
                           v-if="inputVisible1"
                           v-model="inputValue1"
                           ref="saveTagInput1Ref"
                           size="small"
                           @change="colorsInputConfirm1"></el-color-picker>
          <el-button v-else class="button-new-tag" size="small" @click="showInput1">添加颜色</el-button>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="pageCfgDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="pageCfgChangeOk">确 定</el-button>
        </div>
      </template>
    </el-dialog>

  </div>
</template>


<script setup>
import LeftRight from '@/components/Configure/setLayout/leftRightStr';
import UpDown from '@/components/Configure/setLayout/upDownStr';
import { queryModel } from '@/api/configure/configuration/layoutModel';
import { queryScene, addScene, updateScene, delScene } from '@/api/configure/configuration/layoutEdit';
import { getToken } from '@/utils/auth';
import { useRouter } from 'vue-router';

const components = reactive({
  LeftRight: markRaw(LeftRight),
  UpDown: markRaw(UpDown)
});

const router = useRouter();

const inputVisible = ref(false);
const inputValue = ref('');
const inputVisible1 = ref(false);
const inputValue1 = ref('');
const load = ref(false);
const total = ref(0);
const total1 = ref(0);
const queryForm = ref({
  pageNum: 1,
  pageSize: 10
});
const sceneList = ref([]);
const addSceneDialogVisible = ref(false);
const sceneDialogTitle = ref('');
const sceneForm = ref({
  achieveName: '',
  achieveContent: {}
});
const selectModelDialogVisible = ref(false);
const modelPagination = ref({
  pageNum: 1,
  pageSize: 10
});
const modelList = ref([]);
const bindComponentsDialogVisible = ref(false);
const bindComponentsData = ref({
  sceneData: {}
});
const pageCfgDialogVisible = ref(false);
const pageCfg = ref({
  styleData: {
    colors: [],
    colors1: [],
    region: ''
  }
});
const colors = ref([]);
const colors1 = ref([]);
const pageData = ref({
  width: null,
  height: null
});

const getList = () => {
  console.log(queryForm.value);
  load.value = true;
  queryScene(queryForm.value).then(e => {
    sceneList.value = e.rows;
    load.value = false;
    total.value = e.total;
  });
};

const getModelList = () => {
  queryModel(modelPagination.value).then(e => {
    modelList.value = e.rows;
    total1.value = e.total;
  });
};

onMounted(() => {
  getList();
  getModelList();
});
const colorsChange = (i, k) => {
  pageCfg.value.styleData.colors[k] = i;
};
const colorsChange1 = (i, k) => {
  pageCfg.value.styleData.colors1[k] = i;
};
const colorsClose = (tag) => {
  pageCfg.value.styleData.colors.splice(pageCfg.value.styleData.colors.indexOf(tag), 1);
};
const colorsClose1 = (tag) => {
  pageCfg.value.styleData.colors1.splice(pageCfg.value.styleData.colors1.indexOf(tag), 1);
};

const $detectingNullValues = inject('$detectingNullValues');

const colorsInputConfirm = () => {
  let value = inputValue.value;
  if (value) {
    $detectingNullValues(pageCfg.value, ['styleData', 'colors', 0]);
    pageCfg.value.styleData.colors.push(value);
    colors.value.push(value);
  }
  inputVisible.value = false;
  inputValue.value = '';
};
const colorsInputConfirm1 = () => {
  let value = inputValue1.value;
  if (value) {
    $detectingNullValues(pageCfg.value, ['styleData', 'colors1', 0]);
    pageCfg.value.styleData.colors1.push(value);
    colors1.value.push(value);
  }
  inputVisible1.value = false;
  inputValue1.value = '';
};
const showInput = () => {
  inputVisible.value = true;
};
const showInput1 = () => {
  inputVisible1.value = true;
};
const queryScenes = () => {
  getList();
};
const addSceneBtnClick = () => {
  sceneDialogTitle.value = '添加场景';
  addSceneDialogVisible.value = true;
  sceneForm.value = {
    achieveId: null,
    achieveName: '',
    achieveContent: {}
  };
};
const selectModel = () => {
  selectModelDialogVisible.value = true;
  modelPagination.value = {
    pageNum: 1,
    pageSize: 10
  };
};
const useModel = (e) => {
  sceneForm.value.achieveContent = JSON.parse(e.templateContent);
  selectModelDialogVisible.value = false;
  modelPagination.value = {
    pageNum: 1,
    pageSize: 10
  };
};
const addSceneOk = () => {
  addScene({
    achieveName: sceneForm.value.achieveName,
    achieveContent: JSON.stringify(sceneForm.value.achieveContent)
  }).then(e => {
    ElMessage({
      message: '添加成功',
      type: 'success'
    });
    getList();
    addSceneDialogVisible.value = false;
  });
};
const delSceneOk = (e) => {
  delScene({
    achieveId: e
  }).then(v => {
    ElMessage({
      message: '删除成功',
      type: 'success'
    });
    getList();
  });
};
const querySceneInfo = (e) => {
  sceneDialogTitle.value = '修改场景';
  addSceneDialogVisible.value = true;
  sceneForm.value = {
    achieveId: e.achieveId,
    achieveName: e.achieveName,
    achieveContent: JSON.parse(e.achieveContent)
  };
};
const upDateSceneOk = () => {
  updateScene({
    achieveId: sceneForm.value.achieveId,
    achieveName: sceneForm.value.achieveName,
    achieveContent: JSON.stringify(sceneForm.value.achieveContent)
  }).then(e => {
    ElMessage({
      message: '修改成功',
      type: 'success'
    });
    getList();
    addSceneDialogVisible.value = false;
  });
};
const bindComponents = (e) => {
  bindComponentsDialogVisible.value = true;
  bindComponentsData.value = {
    ...e,
    sceneData: JSON.parse(e.achieveContent)
  };
  nextTick(() => {
    pageCfg.value = bindComponentsData.value.sceneData.pageCfg || {};
    if (!pageCfg.value.styleData) {
      pageCfg.value.styleData = {};
    }
    if (!pageCfg.value.styleData?.colors) {
      pageCfg.value.styleData['colors'] = [];
    }
    if (!pageCfg.value.styleData?.colors1) {
      pageCfg.value.styleData['colors1'] = [];
    }
    if (!pageCfg.value.styleData?.region) {
      pageCfg.value.styleData['region'] = '';
    }
    colors.value = JSON.parse(JSON.stringify(pageCfg.value.styleData.colors || '[]'));
    colors1.value = JSON.parse(JSON.stringify(pageCfg.value.styleData.colors1 || '[]'));

    if (pageCfg.value.sizeType === 1) {
      pageData.value = {
        width: pageCfg.value.width,
        height: pageCfg.value.height
      };
    }
    if (pageCfg.value.sizeType === 2) {
      const containerRef = ref();
      let containerWidth = containerRef.value.offsetWidth;
      let containerHeight = containerRef.value.offsetHeight;
      let ratio = pageCfg.value.height / pageCfg.value.width;
      let ratio1 = pageCfg.value.width / pageCfg.value.height;
      if (containerWidth * ratio < containerHeight) {
        pageData.value = {
          width: containerWidth,
          height: containerWidth * ratio
        };
      } else {
        pageData.value = {
          width: containerHeight * ratio1,
          height: containerHeight
        };
      }
    }
    if (pageCfg.value.sizeType === 3) {
      pageData.value = {
        width: null,
        height: null
      };
    }
  });
};
const bindComponentsOk = () => {
  updateScene({
    achieveId: bindComponentsData.value.achieveId,
    achieveName: bindComponentsData.value.achieveName,
    achieveContent: JSON.stringify(bindComponentsData.value.sceneData)
  }).then(e => {
    ElMessage({
      message: '绑定成功',
      type: 'success'
    });
    getList();
    bindComponentsDialogVisible.value = false;
  });
};
const toPageCfg = () => {
  pageCfgDialogVisible.value = true;
};
const pageCfgChangeOk = () => {
  if (pageCfg.value.sizeType === 1) {
    pageData.value = {
      width: pageCfg.value.width,
      height: pageCfg.value.height
    };
  }
  if (pageCfg.value.sizeType === 2) {
    const containerRef = ref();
    let containerWidth = containerRef.value.offsetWidth;
    let containerHeight = containerRef.value.offsetHeight;
    let ratio = pageCfg.value.height / pageCfg.value.width;
    let ratio1 = pageCfg.value.width / pageCfg.value.height;
    if (containerWidth * ratio < containerHeight) {
      pageData.value = {
        width: containerWidth,
        height: containerWidth * ratio
      };
    } else {
      pageData.value = {
        width: containerHeight * ratio1,
        height: containerHeight
      };
    }
  }
  if (pageCfg.value.sizeType === 3) {
    pageData.value = {
      width: null,
      height: null
    };
  }
  bindComponentsData.value.sceneData.pageCfg = pageCfg.value;
  pageCfgDialogVisible.value = false;
};
const getImg = async (file) => {
  pageCfg.value['bg'] = file.data.url.replaceAll('127.0.0.1', '10.11.40.122');
};
const viewDetails = (e) => {
  router.push({ path: '/sceneView', query: { achieveId: e.achieveId } });
};
</script>


<style lang="less" scoped>

:deep(.avatar-uploader) {
  .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }

  .el-upload:hover {
    border-color: #409EFF;
  }
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}

.avatar {
  width: 178px;
  height: 178px;
  display: block;
}

.layout {
  width: 22vw;
  height: 500px;
  border: 1px solid #0003;
  background-repeat: no-repeat;
  background-size: 100% 100%;
}

.miniLayout {
  width: 30px;
  height: 30px;
  border: 1px solid #0003;
  pointer-events: none;
}

.useModel {
  width: 50px;
  height: 50px;
  border: 1px solid #DCDFE6;
  line-height: 50px;
  text-align: center;
  cursor: pointer;

  &:hover {
    border-color: #409EFF;

    i {
      color: #409EFF;
    }
  }
}

.modelListItem {
  width: 200px;
  height: 220px;
  display: inline-block;
  margin: 8px;

  .modelListItemContent {
    width: 100%;
    height: 200px;
    border: 1px solid #0003;
    vertical-align: top;
    background-repeat: no-repeat;
    background-size: 100% 100%;
  }

  .modelListItemName {
    width: 100%;
    height: 20px;
    line-height: 20px;
    text-align: center;
  }

  .blankModel {
    width: 100%;
    height: 200px;
    border: 1px solid #409EFF;
    vertical-align: top;
  }
}

.bindComponents {
  width: 100%;
  height: calc(100vh - 70px - 70px - 60px - 6px);
  position: relative;
  overflow: auto;

  .scene {
    position: absolute;
    left: 0;
    top: 0;
    //left: 50%;
    //top: 50%;
    //transform: translate(-50%, -50%);
    border: 1px solid #0003;
    background-repeat: no-repeat;
    background-size: 100% 100%;
  }
}

:deep(.el-tag) .el-icon-close {
  vertical-align: top;
  line-height: 32px;
}

:deep(.button-new-tag) {
  vertical-align: top;
}

:deep(.input-new-tag) {
  vertical-align: top;
}
</style>
