<template>
  <div
    id="review_Email"
    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-position="" label-width="">
        <el-row>
          <el-col :lg="24" :md="24" :span="24">
            <el-form-item style="margin-right: 20px">
              <el-input
                v-model.trim="search.cardNumber"
                :placeholder="t('card.Form.f24')"
                class="crm-border-radius-no"
                clearable
                @keyup.enter="toSearch"
              ></el-input>
            </el-form-item>
            <el-form-item>
              <el-select
                v-model="search.status"
                :placeholder="t('card.Form.f45')"
                class="crm-border-radius-no"
                clearable
                @change="toSearch"
              >
                <el-option
                  v-for="item in statusOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button class="crm-border-radius-no crm-border-left-no" @click="toSearch">
                <el-icon><Search /></el-icon>
              </el-button>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item v-if="display['R-CardConfig-Import'].show">
          <div class="search_action_btn">
            <span class="crm-cursor delete active" @click="Upload">
              {{ t('R-CardConfig-Import') }}
            </span>
          </div>
        </el-form-item>
        <el-form-item v-if="display['R-CardConfig-Delete'].show">
          <div class="search_action_btn">
            <span class="crm-cursor delete active" @click="deleteAll">
              {{ t('R-CardConfig-Delete') }}
            </span>
          </div>
        </el-form-item>
      </el-form>

      <div class="card-mock-demo" style="margin: 30px 0">
        <el-table
          :data="mock_tableData"
          stripe
          style="margin-top: 20px; width: 100%"
          @selection-change="handleSelectionChange"
        >
          <el-table-column align="left" type="selection" width="55"> </el-table-column>
          <el-table-column :label="t('card.Form.f24')" align="left" prop="cardNumber" />
          <el-table-column :label="t('card.Form.f45')" align="left" prop="status">
            <template #default="scope">
              <span v-if="scope.row.status == 3" class="state crm_state_gray">
                {{ t('State.Used') }}
              </span>
              <span v-else-if="scope.row.status == 2" class="state crm_state_orange">
                {{ t('State.InUse') }}
              </span>
              <span v-else class="state crm_state_yellow">
                {{ t('State.NotUsed') }}
              </span>
            </template>
          </el-table-column>
          <el-table-column prop="" align="center" :label="t('Label.Action')">
            <template #default="scope">
              <el-dropdown trigger="click" @command="handleCommand">
                <span class="el-dropdown-link crm-cursor">
                  <el-icon style="font-weight: bold; font-size: 20px">
                    <MoreFilled />
                  </el-icon>
                </span>
                <template #dropdown>
                  <el-dropdown-menu>
                    <el-dropdown-item
                      v-if="display['R-CardConfig-Update'].show"
                      :command="{ type: 2, row: scope.row }"
                    >
                      <el-icon><Edit /></el-icon>
                      {{ t('R-CardConfig-Update') }}
                    </el-dropdown-item>
                    <el-dropdown-item
                      v-if="display['R-CardConfig-Delete'].show"
                      :command="{ type: 1, row: scope.row }"
                    >
                      <el-icon><Delete /></el-icon>
                      {{ t('R-CardConfig-Delete') }}
                    </el-dropdown-item>
                  </el-dropdown-menu>
                </template>
              </el-dropdown>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>
    <PagePagination
      :pager-info="pagerInfo"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />
    <!-- 上传弹出 -->
    <el-dialog
      v-model="dialogCheckUpload"
      :title="t('R-SynonymTransfer-Upload')"
      center
      custom-class="dialog_header_w"
      width="600px"
    >
      <div
        v-loading="fileLoading"
        class="dia-content"
        element-loading-background="rgba(43, 48, 67, 0.65)"
        element-loading-spinner="el-icon-loading"
      >
        <div class="uploadBox">
          <div class="title">
            <div class="tit"></div>
            <div>
              {{ t('Marketing.SampleDownload') }}
              <span class="demo crm-cursor" @click="exportAgents">Demo</span>
            </div>
          </div>
          <div class="upload">
            <el-upload
              ref="uploadRef"
              :action="action"
              accept=".xlsx"
              :data="{ name: name }"
              :headers="AccessToken"
              :show-file-list="false"
              :auto-upload="false"
              :limit="1"
              :on-exceed="handleExceed"
              :on-success="handleAvatarSuccess"
              :on-change="handlePreview"
            >
              <template #trigger>
                <el-button type="primary">
                  {{ t('Marketing.SelectFile') }}
                </el-button>
              </template>
            </el-upload>
            <span v-if="file" style="margin-left: 10px">{{ file }}</span>
            <span v-else style="margin-left: 10px">
              {{ t('Marketing.NoFileSelected') }}
            </span>
          </div>
        </div>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitUpload()">
            {{ t('Btn.Confirm') }}
          </el-button>
          <el-button @click="Cancel">
            {{ t('Btn.Cancel') }}
          </el-button>
        </div>
      </template>
    </el-dialog>

    <el-dialog
      v-if="dialogCheck"
      v-model="dialogCheck"
      :title="t('R-CardConfig')"
      :rules="rules"
      width="900px"
    >
      <el-form
        ref="dialogFormRef"
        :rules="rules"
        :model="form"
        label-width="130px"
        label-position="right"
        class="business-edit-form"
      >
        <el-form-item prop="cardNumber" :label="t('card.Form.f24')">
          <el-input v-model="form.cardNumber" disabled></el-input>
        </el-form-item>

        <el-form-item prop="status" :label="t('card.Form.f45')">
          <el-select v-model="form.status" :placeholder="t('vaildate.select.empty')">
            <el-option
              v-for="item in statusOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogCheck = false">
            {{ t('Ucard.Business.p32') }}
          </el-button>
          <el-button type="primary" @click="cardNumberUpdate">
            {{ t('card.Btn.Confirm') }}
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
  import { ref, reactive, computed, onMounted, watch, inject, nextTick } from 'vue'
  import { useI18n } from 'vue-i18n'
  import { ElMessage, ElMessageBox } from 'element-plus'
  import { Search, MoreFilled, Operation, Edit, Delete } from '@element-plus/icons-vue'
  import PagePagination from '@/components/pagePagination'
  import Service from '@/service/ucard'
  import Config from '@/config/index'
  import { exportExcel } from '@/utils/export'

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

  // Refs
  const formRef = ref(null)
  const dialogFormRef = ref(null)
  const uploadRef = ref(null)
  const pictLoading = ref(false)
  const dialogCheckUpload = ref(false)
  const dialogCheck = ref(false)
  const file = ref('')
  const name = ref('')
  const fileLoading = ref(false)

  // Constants
  const action = Config.Host85 + '/wasabi/card/number/import'
  const url = Config.Host85

  // 定义选项数组
  const statusOptions = [
    { value: 1, label: t('State.NotUsed') },
    { value: 2, label: t('State.InUse') },
    { value: 3, label: t('State.Used') },
  ]

  // Reactive data
  const search = reactive({
    status: '',
    cardNumber: '',
  })

  const form = reactive({
    status: '',
    cardNumber: '',
  })

  const mock_tableData = ref([])
  const multipleSelection = ref([])

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

  const rules = reactive({
    idType: [
      {
        required: true,
        message: t('vaildate.select.empty'),
        trigger: 'blur',
      },
    ],
    country: [
      {
        required: true,
        message: t('vaildate.select.empty'),
        trigger: 'blur',
      },
    ],
  })

  // Computed properties
  const display = computed(() => {
    const displayStr = Session.Get('display', true)
    return displayStr ? JSON.parse(displayStr) : {}
  })

  const user = computed(() => {
    const userStr = Session.Get('user', true)
    return userStr ? JSON.parse(userStr) : {}
  })

  const AccessToken = computed(() => {
    return {
      'Access-Token': Session.Get('access_token'),
    }
  })

  // Methods
  const deleteAll = async () => {
    if (!multipleSelection.value.length) {
      return
    }

    try {
      await ElMessageBox.confirm(t('Msg.Delete'), t('Msg.SystemPrompt'), {
        confirmButtonText: t('Btn.Confirm'),
        cancelButtonText: t('Btn.Cancel'),
        type: 'warning',
      })

      const res = await Service.cardNumberDelete({
        ids: multipleSelection.value,
      })
      if (res.code == Code.StatusOK) {
        ElMessage.success(t('Msg.DeleteSuccess'))
        searchFunc()
      } else {
        ElMessage.error(res.msg)
      }
    } catch (error) {
      // 用户取消删除
    }
  }

  const handleCommand = (command) => {
    switch (command.type) {
      case 1:
        multipleSelection.value = [command.row.id]
        deleteAll()
        break
      case 2: {
        Object.assign(form, JSON.parse(JSON.stringify(command.row)))
        dialogCheck.value = true
        break
      }
    }
  }

  //选择多项
  const handleSelectionChange = (val) => {
    multipleSelection.value = []
    val.forEach((item) => {
      multipleSelection.value.push(item.id)
    })
  }

  const Cancel = () => {
    dialogCheckUpload.value = false
  }

  const submitUpload = () => {
    if (!file.value) {
      ElMessage.warning(t('Msg.upload'))
      return
    }
    fileLoading.value = true
    uploadRef?.value.submit()
  }

  const handleAvatarSuccess = (res) => {
    if (res.code == 200) {
      ElMessage.success(t('Msg.uploadSuccess'))
      Cancel()
      toSearch()
    } else {
      ElMessage.error(res.msg)
    }
    fileLoading.value = false
  }

  const handlePreview = (file) => {
    if (!file.percentage) {
      file.value = file.name
    } else {
      file.value = ''
    }
  }

  const handleExceed = (files) => {
    if (uploadRef.value) {
      uploadRef.value.clearFiles()
      const latest = files && files.length ? files[0] : null
      if (latest) {
        file.value = latest.name || ''
        nextTick(() => {
          if (uploadRef.value && uploadRef.value.handleStart) {
            uploadRef.value.handleStart(latest)
          }
        })
      }
    }
  }

  const beforeAvatarUpload = (file) => {
    const isLt2M = file.size / 1024 / 1024 < 3

    if (!isLt2M) {
      ElMessage.error(t('news_add_field.Des.item1'))
    }
    return isLt2M
  }

  //导出
  const exportAgents = async () => {
    exportExcel(
      pigeon,
      '/wasabi/card/number/template/export',
      { ...search },
      'Card_Number_Template'
    )
  }

  const Upload = () => {
    dialogCheckUpload.value = true
  }

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

  // 列表
  const searchFunc = async () => {
    pictLoading.value = true

    if (!display.value['R-CardConfig-List']?.show) {
      ElMessage.warning(t('Msg.NotDisplay'))
      pictLoading.value = false
      return
    }

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

    if (res.code == Code.StatusOK) {
      mock_tableData.value = res.data
      if (res.page != null) {
        pagerInfo.rowTotal = res.page.rowTotal
        pagerInfo.pageTotal = res.page.pageTotal
      } else {
        pagerInfo.rowTotal = 0
      }
      ElMessage.success(t('Msg.SearchSuccess'))
    } else {
      ElMessage.error(res.msg)
    }
    pictLoading.value = false
  }

  const handleSizeChange = (val) => {
    pagerInfo.row = val
    searchFunc()
  }

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

  const cardNumberUpdate = async () => {
    try {
      const valid = await dialogFormRef.value.validate()
      if (!valid) return

      const res = await Service.cardNumberUpdate({ ...form })
      if (res.code == 200) {
        Object.assign(form, {
          country: null,
          idType: null,
        })
        dialogCheck.value = false
        toSearch()
      } else {
        ElMessage.error(res.msg)
      }
    } catch (error) {
      console.log(error)
      ElMessage.error(t('Msg.SystemError'))
    }
  }

  // Lifecycle hooks
  onMounted(() => {
    searchFunc()
  })
</script>

<style lang="scss" scoped>
  #review_Email {
    .crm_search {
      .search_action_btn {
        .delete {
          background-color: #a1a1a1;
        }

        .delete.active {
          background-color: #368fec;
        }
      }
    }

    .el-table .state {
      display: inline-block;
      min-width: 80px;
      max-width: 150px;
      box-sizing: border-box;
      line-height: 1.5;
      border-radius: 2px;
      padding: 2px 10px;
      color: #ffffff;
    }

    .crm_switch {
      :deep(.el-form-item__content) {
        text-align: left;
      }
    }
  }
</style>
<style lang="scss">
  #review_Email {
    .dialog_header_w {
      .crm_search_down,
      .el-input__inner {
        width: 400px;
      }
      .number-range-input {
        .el-input__inner {
          width: 190px !important;
        }
      }
    }
    .uploadBox {
      padding: 25px;
      @include bg_gray_7();
      .title {
        display: flex;
        justify-content: space-between;
        .tit {
          font-weight: bold;
        }
        .demo {
          @include font_blue_btn_1();
        }
      }
      .input-all {
        margin: 15px 0;
      }
      .upload {
        display: flex;
        align-items: center;
      }
      .btn-foot {
        text-align: right;
      }
    }
    .width-100 {
      width: 100% !important;
    }
  }
</style>
