<template>
  <div
    id="card_Blockchain"
    v-loading="pictLoading"
    class="view"
    :element-loading-background="'rgba(43, 48, 67, 0.65)'"
    :element-loading-spinner="'el-icon-loading'"
  >
    <div class="crm_search">
      <el-form ref="formRef" :model="search" label-width="">
        <el-row>
          <el-col :span="24" :md="24" :lg="24">
            <el-form-item style="margin-right: 10px">
              <el-input
                v-model.trim="search.alias"
                class="crm-border-radius-no"
                clearable
                :placeholder="t('Placeholder.Input')"
                @keyup.enter="toSearch"
              >
                <template #prepend>
                  <span class="crm-cursor crm-border-radius-no">
                    {{ t('Ucard.Blockchain.pageT1') }}
                  </span>
                </template>
              </el-input>
            </el-form-item>
            <el-form-item style="margin-right: 10px">
              <el-select
                v-model="search.blockchain"
                class="crm-border-radius-no"
                clearable
                :placeholder="t('Ucard.Blockchain.pageT2')"
                @change="toSearch"
              >
                <el-option v-for="(item, index) in opts" :key="index" :label="item" :value="item" />
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-select
                v-model="search.enableStatus"
                class="crm-border-radius-no"
                clearable
                :placeholder="t('Ucard.Blockchain.pageT3')"
                @change="toSearch"
              >
                <el-option
                  v-for="(value, key) in enableStatus"
                  :key="key"
                  :label="t(value)"
                  :value="key"
                />
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button
                class="crm-border-radius-no crm-border-left-no"
                :icon="Search"
                @click="toSearch"
              ></el-button>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item>
          <el-button
            v-if="display['R-Card-Blockchain-Add']?.show"
            class=""
            type="primary"
            :icon="Plus"
            @click="openAddDialog"
          >
            {{ t('R-Card-Blockchain-Add') }}
          </el-button>
          <el-button
            v-if="display['R-Card-Blockchain-Delete']?.show"
            :disabled="!multipleSelection.length"
            :type="multipleSelection.length ? 'primary' : 'info'"
            :icon="Minus"
            @click="toDelete"
          >
            {{ t('R-Card-Blockchain-Delete') }}
          </el-button>
        </el-form-item>
      </el-form>
    </div>
    <el-table
      :data="mock_tableData"
      stripe
      style="width: 100%"
      @selection-change="handleSelectionChange"
    >
      <el-table-column align="left" type="selection" width="55"> </el-table-column>
      <el-table-column prop="alias" align="left" :label="t('Ucard.Blockchain.pageT1')">
        <template #default="{ row }">
          {{ row.alias || '--' }}
        </template>
      </el-table-column>
      <el-table-column prop="blockchain" align="left" :label="t('Ucard.Blockchain.pageT2')">
        <template #default="{ row }">
          {{ row.blockchain || '--' }}
        </template>
      </el-table-column>
      <el-table-column prop="enableStatus" align="left" :label="t('Ucard.Blockchain.pageT3')">
        <template #default="{ row }">
          <el-switch
            v-model="row.enableStatus"
            :disabled="!display['R-Card-Blockchain-Edit']?.show"
            :active-text="t(enableStatus[1])"
            :active-value="1"
            :inactive-text="t(enableStatus[0])"
            :inactive-value="0"
            active-color="#368FEC"
            inactive-color="#EB3F57"
            class="crm_switch crm_switch_width"
            @change="() => changeEnable(row)"
          >
          </el-switch>
        </template>
      </el-table-column>
      <el-table-column prop="ctrl" align="center" :label="t('Label.Action')">
        <template #default="{ row }">
          <el-dropdown trigger="click" @command="handleCommand">
            <span class="el-dropdown-link crm-cursor">
              <i style="font-weight: bold; font-size: 20px" class="iconfont iconcaidan"></i>
            </span>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item
                  v-if="display['R-Card-Blockchain-Edit']?.show"
                  :command="{ type: 'editor', row: row }"
                >
                  <el-icon><Edit /></el-icon>
                  <span>{{ t('R-Card-Blockchain-Edit') }}</span>
                </el-dropdown-item>
                <el-dropdown-item
                  v-if="display['R-Card-Blockchain-Delete']?.show"
                  :command="{ type: 'delete', row: row }"
                >
                  <el-icon><Delete /></el-icon>
                  <span>{{ t('R-Card-Blockchain-Delete') }}</span>
                </el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </template>
      </el-table-column>
    </el-table>
    <PagePagination
      :pager-info="pagerInfo"
      @current-change="handleCurrentChange"
      @size-change="handleSizeChange"
    />

    <!-- 新增 -->
    <el-dialog
      v-model="addDialogVisible"
      :title="t(isEdit ? 'Ucard.Blockchain.title1' : 'Ucard.Blockchain.title2')"
      width="500px"
      :close-on-click-modal="false"
    >
      <el-form ref="addFormRef" :model="addForm" :rules="addRules" label-width="120px">
        <el-form-item :label="`${t('Ucard.Blockchain.pageT1')}:`" prop="alias">
          <el-input v-model="addForm.alias" :placeholder="t('Ucard.Blockchain.addP1')"></el-input>
        </el-form-item>
        <el-form-item :label="`${t('Ucard.Blockchain.pageT2')}:`" prop="blockchain">
          <el-select
            v-model="addForm.blockchain"
            :disabled="isEdit"
            :placeholder="t('Ucard.Blockchain.addP2')"
          >
            <el-option v-for="item in opts" :key="item" :label="item" :value="item"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item
          style="text-align: left"
          :label="`${t('Ucard.Blockchain.pageT3')}:`"
          prop="enableStatus"
        >
          <el-switch
            v-model="addForm.enableStatus"
            :active-text="t(enableStatus[1])"
            :active-value="1"
            :inactive-text="t(enableStatus[0])"
            :inactive-value="0"
            active-color="#368FEC"
            class="crm_switch crm_switch_width"
            inactive-color="#EB3F57"
          >
          </el-switch>
        </el-form-item>
        <el-form-item :label="`${t('Ucard.Blockchain.pageT4')}:`" prop="listType">
          <el-select
            v-model="addForm.listType"
            :placeholder="t('Ucard.Blockchain.addP4')"
            @change="changeType"
          >
            <el-option
              v-for="(item, key) in listType"
              :key="key"
              :label="t(item)"
              :value="key"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item
          v-if="addForm.listType == 1"
          :label="`${t('Ucard.Blockchain.pageT5')}:`"
          prop="whitelist"
        >
          <el-select
            v-model="addForm.whitelist"
            multiple
            :placeholder="t('Ucard.Blockchain.addP5')"
          >
            <el-option
              v-for="item in userList"
              :key="item.uniqueId"
              :label="`${item.cId} / ${item.email}`"
              :value="item.uniqueId"
            />
          </el-select>
        </el-form-item>
        <el-form-item
          v-if="addForm.listType == 2"
          :label="`${t('Ucard.Blockchain.pageT6')}:`"
          prop="blacklist"
        >
          <el-select
            v-model="addForm.blacklist"
            multiple
            :placeholder="t('Ucard.Blockchain.addP6')"
          >
            <el-option
              v-for="item in userList"
              :key="item.uniqueId"
              :label="`${item.cId} / ${item.email}`"
              :value="item.uniqueId"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="addDialogVisible = false">{{ t('Btn.Cancel') }} </el-button>
          <el-button type="primary" :loading="addLoading" @click="handleAddConfirm"
            >{{ t('Btn.Confirm') }}
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
  import { ref, reactive, computed, onMounted, inject } from 'vue'
  import { useI18n } from 'vue-i18n'
  import { ElMessageBox } from 'element-plus'
  import Service from '@/service/ucard'
  import Config from '@/config/index'
  import { enableStatus } from '@/enum/enum'
  import { listType } from '@/enum/card/blockchain'
  import PagePagination from '@/components/pagePagination/index.vue'
  import { Delete, Edit, Minus, Operation, Plus, Search } from '@element-plus/icons-vue'

  const { t } = useI18n()
  const { Code } = Config
  const Session = inject('session')
  const pigeon = inject('pigeon')

  // 响应式数据
  const opts = ref([])
  const userList = ref([])
  const pictLoading = ref(false)
  const mock_tableData = ref([])
  const formRef = ref(null)
  const addFormRef = ref(null)
  const addDialogVisible = ref(false)
  const isEdit = ref(false)
  const addLoading = ref(false)
  const multipleSelection = ref([])

  const search = reactive({
    alias: '',
    blockchain: '',
    enableStatus: '',
  })

  const pagerInfo = reactive({
    row: 10,
    current: 1,
    pageTotal: 0,
    rowTotal: 0,
  })

  const addForm = reactive({
    alias: '',
    blockchain: '',
    enableStatus: 0,
    listType: undefined,
    whitelist: [],
    blacklist: [],
  })

  // 计算属性
  const display = computed(() => {
    return JSON.parse(Session.Get('display', true))
  })

  const addRules = computed(() => ({
    alias: [
      {
        required: true,
        message: t('Ucard.Blockchain.addP1'),
        trigger: 'blur',
      },
    ],
    blockchain: [
      {
        required: true,
        message: t('Ucard.Blockchain.addP2'),
        trigger: 'blur',
      },
    ],
    enableStatus: [
      {
        required: true,
        message: t('Ucard.Blockchain.addP3'),
        trigger: 'blur',
      },
    ],
  }))

  // 生命周期
  onMounted(() => {
    getBlockchainList()
    getUserList()
    searchFunc()
  })

  // 方法
  // 获取列表数据
  const searchFunc = async () => {
    pictLoading.value = true
    if (!display.value['R-Card-Blockchain-Page']?.show) {
      pigeon.warning(t('Msg.NotDisplay'))
      pictLoading.value = false
      return
    }

    const res = await Service.getBlockchainPage({
      ...search,
      page: {
        current: pagerInfo.current,
        row: pagerInfo.row,
      },
    })

    if (res.code == Code.StatusOK) {
      mock_tableData.value = res.data.map((item) => {
        const { whitelist, blacklist, ...rest } = item
        return {
          ...rest,
          listType: whitelist ? '1' : blacklist ? '2' : undefined,
          whitelist: whitelist?.match(/[^,]+/g) || [],
          blacklist: blacklist?.match(/[^,]+/g) || [],
        }
      })

      if (res.page != null) {
        pagerInfo.rowTotal = res.page.rowTotal
        pagerInfo.pageTotal = res.page.pageTotal
      } else {
        pagerInfo.rowTotal = 0
      }

      pigeon.success(t('Msg.SearchSuccess'))
    } else {
      pigeon.error(res.msg)
    }

    pictLoading.value = false
  }

  // 选择多项
  const handleSelectionChange = (val) => {
    multipleSelection.value = val.map((item) => item.id)
  }

  // 删除
  const toDelete = () => {
    handleDelete(multipleSelection.value)
  }

  const changeType = () => {
    // 可以在这里处理类型变化逻辑
  }

  // 搜索
  const toSearch = () => {
    pagerInfo.current = 1
    searchFunc()
  }

  const getBlockchainList = async () => {
    const res = await Service.getBlockchains()
    if (res.code == Code.StatusOK) {
      opts.value = res.data
    } else {
      pigeon.error(res.msg)
    }
  }

  const getUserList = async () => {
    const res = await Service.cardUserList()
    if (res.code == Code.StatusOK) {
      userList.value = res.data
    } else {
      pigeon.error(res.msg)
    }
  }

  // 分页返回数据
  const handleSizeChange = (val) => {
    pagerInfo.row = val
    searchFunc()
  }

  const handleCurrentChange = (val) => {
    pagerInfo.current = val
    searchFunc()
  }

  // 处理下拉菜单命令
  const handleCommand = (command) => {
    if (command.type === 'editor') {
      Object.assign(addForm, command.row)
      isEdit.value = true
      addDialogVisible.value = true
    } else if (command.type === 'delete') {
      handleDelete([command.row.id])
    }
  }

  // 打开新增对话框
  const openAddDialog = () => {
    Object.assign(addForm, {
      alias: '',
      blockchain: '',
      enableStatus: 0,
      whitelist: [],
      blacklist: [],
    })
    isEdit.value = false
    addDialogVisible.value = true
  }

  // 修改启用状态
  const changeEnable = async (row) => {
    try {
      const res = await Service.updateBlockchain({
        id: row.id,
        alias: row.alias,
        enableStatus: row.enableStatus,
        blockchain: row.blockchain,
      })

      if (res.code == 200) {
        pigeon.success(t('card.Info.t27'))
        searchFunc()
      } else {
        pigeon.error(res.msg)
      }
    } catch (error) {
      pigeon.error(t('Msg.SystemError'))
    }
  }

  // 确认新增/编辑
  const handleAddConfirm = async () => {
    if (!addFormRef.value) return

    const valid = await addFormRef.value.validate()
    if (!valid) return

    addLoading.value = true
    try {
      const { blacklist, listType, enableStatus, whitelist, ...rest } = addForm

      const params = {
        ...rest,
        enableStatus: enableStatus,
        whitelist: listType === '1' ? whitelist.join(',') : undefined,
        blacklist: listType === '2' ? blacklist.join(',') : undefined,
      }

      const res = isEdit.value
        ? await Service.updateBlockchain(params)
        : await Service.addBlockchain(params)

      if (res.code == Code.StatusOK) {
        pigeon.success(t('Msg.SaveSuccess'))
        addDialogVisible.value = false
        searchFunc() // 刷新列表
      } else {
        pigeon.error(res.msg)
      }
    } catch (error) {
      pigeon.error(t('Msg.SaveFail'))
    } finally {
      addLoading.value = false
    }
  }

  // 删除
  const handleDelete = async (ids) => {
    try {
      await ElMessageBox.confirm(
        t('Ucard.Blockchain.deleteConfirm'),
        t('Ucard.Blockchain.deleteTitle'),
        {
          confirmButtonText: t('Btn.Confirm'),
          cancelButtonText: t('Btn.Cancel'),
          type: 'warning',
        }
      )

      const res = await Service.deleteBlockchain({ ids })
      if (res.code == Code.StatusOK) {
        pigeon.success(t('Msg.DeleteSuccess'))
        searchFunc() // 刷新列表
      } else {
        pigeon.error(res.msg)
      }
    } catch (error) {
      if (error !== 'cancel') {
        pigeon.error(t('Msg.DeleteFail'))
      }
    }
  }
</script>
<style scoped lang="scss">
  #card_Blockchain {
    .crm_search {
      .search_action_btn {
        .delete {
          background-color: #a1a1a1;
        }

        .delete.active {
          background-color: #368fec;
        }
      }
    }
  }
</style>
<style lang="scss">
  #card_Blockchain {
    .dialog_header_w {
      .crm_search_down {
        width: 400px;
      }
    }
  }
</style>
