<template>
  <div>
    <vxe-toolbar>
      <template #buttons>
        <el-button size="mini" icon="el-icon-plus" type="primary" @click="addEvent">新增自定义按钮</el-button>
      </template>
    </vxe-toolbar>
    <div class="flex gap-10" style="overflow: auto; height: calc(100vh - 180px)">
      <div style="width: 50%; overflow: auto">
        <el-divider>表头按钮配置</el-divider>
        <vxe-table align="center" min-height="57" border :data="systemBtn" empty-text="点击添加自定义按钮">
          <vxe-column field="label" title="按钮名称"></vxe-column>
          <vxe-column field="type" title="按钮类型"></vxe-column>
          <vxe-column field="buttonStatus" title="按钮状态">
            <template #default> 启用 </template>
          </vxe-column>
          <vxe-column title="操作" align="left" width="250">
            <template #default="{ row }">
              <el-button size="small" type="success" plain @click="selectEvent(row)"> {{ row.eventNum > 0 ? `(${row.eventNum})` : '' }}设置事件 </el-button>
            </template>
          </vxe-column>
        </vxe-table>
        <vxe-table align="center" border :show-header="false" :data="customTableData.filter((o) => o.buttonLocation === 1)" empty-text="请点击新增自定义按钮">
          <vxe-column field="label" title="按钮名称"></vxe-column>
          <vxe-column field="type" title="按钮类型"></vxe-column>
          <vxe-column field="buttonStatus" title="按钮状态">
            <template #default> 启用 </template>
          </vxe-column>
          <vxe-column title="操作" align="left" width="250">
            <template #default="{ row }">
              <el-button size="mini" type="success" plain @click="selectEvent(row)">{{ row.eventNum > 0 ? `(${row.eventNum})` : '' }}设置事件</el-button>
              <el-button size="mini" type="primary" plain @click="editEvent(row)">编辑</el-button>
              <el-button size="mini" type="danger" plain @click="removeEvent(row)">删除</el-button>
            </template>
          </vxe-column>
        </vxe-table>
      </div>
      <div style="width: 50%; overflow: auto">
        <el-divider>行操作按钮配置</el-divider>
        <vxe-table align="center" border :data="actionBtn">
          <vxe-column field="label" title="按钮名称"></vxe-column>
          <vxe-column field="type" title="按钮类型"></vxe-column>
          <vxe-column field="buttonStatus" title="按钮状态">
            <template #default> 启用 </template>
          </vxe-column>
          <vxe-column title="操作" align="left" width="250">
            <template #default="{ row }">
              <el-button size="small" type="success" plain @click="selectEvent(row)"> {{ row.eventNum > 0 ? `(${row.eventNum})` : '' }}设置事件 </el-button>
            </template>
          </vxe-column>
        </vxe-table>
        <vxe-table align="center" border :show-header="false" :data="customTableData.filter((o) => o.buttonLocation === 2)" empty-text="请点击新增自定义按钮">
          <vxe-column field="label" title="按钮名称"></vxe-column>
          <vxe-column field="type" title="按钮类型"></vxe-column>
          <vxe-column field="buttonStatus" title="按钮状态">
            <template #default="{ row }">
              <el-switch
                v-model="row.buttonStatus"
                active-text="启用"
                inactive-text="禁用"
                :active-value="0"
                :inactive-value="1"
                active-color="#13ce66"
                inactive-color="#ff4949"
                @change="disableEvent(row)"
              ></el-switch>
            </template>
          </vxe-column>
          <vxe-column title="操作" align="left" width="250">
            <template #default="{ row }">
              <el-button size="mini" type="success" v-if="row.execType === 2" plain @click="selectEvent(row)">{{ row.eventNum > 0 ? `(${row.eventNum})` : '' }}设置事件</el-button>
              <el-button size="mini" type="primary" plain @click="editEvent(row)">编辑</el-button>
              <el-button size="mini" type="danger" plain @click="removeEvent(row)">删除</el-button>
            </template>
          </vxe-column>
        </vxe-table>
      </div>
    </div>
    <vxe-modal v-model="isShow" title="新增按钮" width="60%" height="80%" :position="{ top: 60 }" show-footer>
      <el-form label-width="120px" size="small">
        <el-form-item label="按钮名称">
          <el-input v-model="showFrom.buttonName" placeholder="请输入按钮名称"></el-input>
        </el-form-item>
        <el-form-item label="展示位置">
          <el-radio-group v-model="showFrom.buttonLocation">
            <el-radio :label="1" :value="1">表头位置</el-radio>
            <el-radio :label="2" :value="2">行数据操作位置</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="展示条件">
          <amis-sdk :amis-json="amisJson" v-model="showFrom.buttonCondition" />
          <!--          <el-input type="textarea" :rows="2" placeholder="请输入内容" v-model="showFrom.buttonCondition"> </el-input>-->
          注：条件sql返回列必须存在主键列，并且where条件必须有主键列约束<br />
          例句:SELECT id from {表名} where {约束条件} and id IN([ids])
        </el-form-item>
        <el-form-item label="按钮样式">
          <div class="flex gap-10">颜色{{ showFrom.color }}<el-color-picker v-model="showFrom.buttonInfo.color" show-alpha :predefine="predefineColors"></el-color-picker></div>
        </el-form-item>
        <el-form-item label="触发事件">
          <el-radio-group v-model="showFrom.execType">
            <el-radio :label="2" :value="2">事件</el-radio>
            <el-radio :label="1" :value="1">链接</el-radio>
          </el-radio-group>
        </el-form-item>
        <template v-if="showFrom.execType !== 1">
          <el-form-item label="弹窗信息">
            <el-radio-group v-model="showFrom.isWindow">
              <el-radio :label="0" :value="0">
                弹窗提示
                <el-tooltip style="cursor: pointer" effect="dark" :content="'选择弹窗提示时，如未填写弹窗提示语则无法触发弹窗'" placement="top">
                  <i class="el-icon-question" />
                </el-tooltip>
              </el-radio>
              <el-radio v-if="showFrom.buttonLocation === 2" :label="1" :value="1">弹窗录入</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="弹窗提示语" v-if="showFrom.isWindow === 0">
            <el-input v-model="showFrom.windowTips" placeholder="请输入弹窗提示语"></el-input>
          </el-form-item>
          <el-form-item label="弹窗字段" v-if="showFrom.isWindow === 1">
            <el-table :data="windowViewColumns.value" height="250">
              <el-table-column label="字段" >
                <template slot-scope="scope">
                  <span>{{scope.row.label}}</span>
                </template>
              </el-table-column>
              <el-table-column label="可见" >
                <template slot-scope="scope">
                  <el-checkbox v-model="scope.row.isShow"></el-checkbox>
                </template>
              </el-table-column>
              <el-table-column label="读写" >
                <template slot-scope="scope">
                  <el-checkbox v-model="scope.row.isChange"></el-checkbox>
                </template>
              </el-table-column>
              <el-table-column label="必填" >
                <template slot-scope="scope">
                  <el-checkbox v-model="scope.row.isRequired"></el-checkbox>
                </template>
              </el-table-column>
            </el-table>
          </el-form-item>
        </template>

        <el-form-item label="选择事件" v-if="showFrom.execType === 2">
          <custom-event ref="customevent" :is-compont="true" :dbSourceId="dataForm.dbSourceId" :model-id="columnData.modelId" :cube-id="dataForm.dbLinkId" @select="selectEventList" />
        </el-form-item>
        <el-form-item label="链接地址" v-if="showFrom.execType === 1">
          <el-input v-model="showFrom.redirectUrl" placeholder="请输入链接地址"></el-input>
          可用变量<template v-for="item in cubeList">
            {{ item.label }}：<el-button type="text">{{ item.value }} </el-button></template
          >
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="isShow = false">取消</el-button>
        <el-button type="primary" @click="saveEvent">保存</el-button>
      </template>
    </vxe-modal>
    <vxe-modal v-model="isEvent" title="选择事件" width="60%" :position="{ top: 60 }" show-footer>
      <custom-event ref="customevent" :is-compont="true" :dbSourceId="dataForm.dbSourceId" :model-id="columnData.modelId" :cube-id="dataForm.dbLinkId" @select="selectEventList" />
      <template #footer>
        <el-button type="primary" @click="saveEvent">保存</el-button>
      </template>
    </vxe-modal>
  </div>
</template>
<script setup>
import { onMounted, ref, watch, computed } from 'vue'
import { addCustomButton, deleteCustomButton, getCustomButton } from '@/api/onlineDev/visualDev'
import { Loading, Message } from 'element-ui'
import { predefineColors } from '@/utils/useUtil'
import CustomEvent from '@/views/form/webDesign/CustomEvent.vue'
import AmisSdk from '@/components/AmisSdk.vue'
import {getDrawingList} from "@/components/Generator/utils/db";
import {loopRelationList} from "@/utils";

const props = defineProps({
  columnData: Object,
  dataForm: Object,
  systemBtn: [],
  actionBtn: [],
  activeName: String
})
const modelId = props?.columnData?.modelId || 0

const amisJson = ref({
  type: 'editor',
  language: 'sql'
})

const customTableData = ref([])

const drawList = loopRelationList(getDrawingList()).map(i =>{ return {label:i.__config__.label,id:i.__vModel__,isShow:false,isChange:false,isRequired:i.__config__.required}})
// watch([() => props.activeName], () => {
//   init()
// })

const cubeList = computed(() => {
  return props.columnData.cubeList.map((item) => {
    return {
      label: item.columnTitle,
      value: '{{ ' + item.columnName + ' }}'
    }
  })
})

const systemBtn = ref([])
const actionBtn = ref([])
const init = async () => {
  const loading = Loading.service({ text: '加载中' })
  const { data } = await getCustomButton(modelId)
  loading.close()
  const { records } = data.data
  customTableData.value = records
    .filter((v) => v.buttonType === 1)
    .map((item) => {
      item.buttonInfo = item.buttonInfo ? JSON.parse(item.buttonInfo || {}) : {}
      item.label = item.buttonName
      item.type = item.buttonType === 1 ? '自定义按钮' : '系统按钮'
      return item
    })

  const systemBtns = records.filter((v) => v.buttonType === 2)
  systemBtn.value = props.systemBtn.map((item) => {
    const find = systemBtns.find((v) => v.buttonName === item.label)
    item.buttonName = item.label
    item.buttonInfo = {
      color: '#409EFF'
    }
    item.buttonLocation = 1
    item.buttonType = 2
    item.buttonStatus = 0
    item.type = '系统按钮'
    item.formId = modelId
    item.eventList = find?.eventList || []
    item.id = find ? find.id : 0
    item.execType = 2
    item.eventNum = find?.eventNum || 0
    return item
  })
  actionBtn.value = props.actionBtn.map((item) => {
    const find = systemBtns.find((v) => v.buttonName === item.label)
    item.buttonName = item.label
    item.buttonInfo = {
      color: '#409EFF'
    }
    item.buttonLocation = 2
    item.buttonType = 2
    item.buttonStatus = 0
    item.type = '系统按钮'
    item.formId = modelId
    item.eventList = find?.eventList || []
    item.eventNum = find?.eventNum || 0
    item.id = find ? find.id : 0
    item.execType = 2
    return item
  })
}
init()
const customevent = ref()
const isShow = ref(false)

const defaultForm = {
  buttonCondition: '',
  buttonLocation: 2,
  buttonInfo: {
    // 事件类型 1-按钮 2-链接
    buttonType: 1,
    // 颜色
    color: '#409EFF'
  },
  buttonName: '',
  execType: 2,
  isWindow: 0,
  windowTips: '',
  buttonStatus: 0,
  buttonType: 1,
  eventList: [],
  formId: modelId,
  id: 0,
  redirectUrl: 'http://'
}
const windowViewColumns = drawList || []
const showFrom = ref({ ...defaultForm })

// 新增按钮
const addEvent = () => {
  showFrom.value = { ...defaultForm }
  isShow.value = true
  windowViewColumns.value = drawList || []
}

const editEvent = (row) => {
  showFrom.value = row
  isShow.value = true
  windowViewColumns.value = row.windowViewColumns
  const list = row.eventList.map((item) => {
    const data = {
      id: item.eventId
    }
    return data
  })
  setTimeout(() => {
    customevent.value.multipass(list)
  }, 100)
  if (showFrom.value.isWindow === 1 && !windowViewColumns.value) {
    windowViewColumns.value = drawList || []
  }else {
   if (row.windowViewColumns){
     try {
       windowViewColumns.value = JSON.parse(row.windowViewColumns)
     }catch (e) {
       windowViewColumns.value = row.windowViewColumns
     }
   }
  }
}

// 保存按钮
const saveEvent = () => {
  if (!showFrom.value.buttonName) {
    Message.error('请输入按钮名称')
    return
  }
  if (showFrom.value.execType === 2 && showFrom.value.buttonType === 1 && !showFrom.value.eventList.length) {
    Message.error('请选择事件')
    return
  }
  if (showFrom.value.execType === 1 && showFrom.value.redirectUrl === 'http://') {
    Message.error('请输入链接地址')
    return
  }
  showFrom.value.buttonInfo = JSON.stringify(showFrom.value.buttonInfo)
  try {
    showFrom.value.windowViewColumns = JSON.stringify(windowViewColumns.value)
  }catch (e) {}
  addCustomButton(modelId, showFrom.value).then((res) => {
    if (res.data.code === 200) {
      Message.success('操作成功')
      isShow.value = false
      isEvent.value = false
      init()
    } else {
      Message.error('新增失败' + res.data.msg)
    }
  })
}

const removeEvent = (row) => {
  customTableData.value = customTableData.value.filter((item) => item !== row)
  deleteCustomButton(modelId, row.id).then((res) => {
    if (res.data.code === 200) {
      Message.success('删除成功')
    }
  })
}

// 禁用按钮
const disableEvent = (row) => {
  row.buttonInfo = JSON.stringify(row.buttonInfo)
  addCustomButton(modelId, row).then((res) => {
    if (res.data.code === 200) {
      Message.success('操作成功')
    }
  })
}

const isEvent = ref(false)
const selectEvent = (row) => {
  showFrom.value = row
  isEvent.value = true
  const list = row.eventList.map((item) => {
    const data = {
      id: item.eventId
    }
    return data
  })
  setTimeout(() => {
    customevent.value.multipass(list)
  }, 100)
}
const selectEventModel = (row) => {
  isEvent.value = true
}
const selectEventList = (row) => {
  showFrom.value.eventList = row.map((item, index) => {
    return {
      eventId: item.id,
      eventSort: index
    }
  })
}
</script>
<style scoped lang="scss"></style>
