<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" label-position="" :model="search" label-width="">
        <el-row>
          <el-col :span="24" :md="24" :lg="24">
            <el-form-item style="margin-right: 10px">
              <el-select
                v-model.trim="search.code"
                filterable
                class="crm-border-radius-no"
                clearable
                :placeholder="t('card.vaildate.v6')"
                @change="toSearch"
              >
                <el-option
                  v-for="item in countryCityList"
                  :key="item.id"
                  :label="lang == 'cn' ? item.cnName : item.enName"
                  :value="item.code"
                />
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-select
                v-model="search.idType"
                class="crm-border-radius-no"
                clearable
                :placeholder="t('Placeholder.Choose')"
                @change="toSearch"
              >
                <el-option
                  v-for="item in idTypeFilterOptions"
                  :key="item.value"
                  :label="t(item.label)"
                  :value="item.value"
                />
              </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-IdTypeConfig-Add'].show">
          <div class="search_action_btn">
            <span class="crm-cursor delete active" @click="approvalAll(1)">
              {{ t('R-IdTypeConfig-Add') }}
            </span>
          </div>
        </el-form-item>
        <el-form-item v-if="display['R-IdTypeConfig-Delete'].show">
          <div class="search_action_btn">
            <span class="crm-cursor delete active" @click="deleteAll">
              {{ t('R-IdTypeConfig-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 prop="code" align="left" :label="t('card.Form.f7')">
            <template #default="scope">
              {{ lang == 'cn' ? scope.row.cnName : scope.row.enName }}
            </template>
          </el-table-column>
          <el-table-column prop="idType" align="left" :label="t('card.Form.f16')">
            <template #default="scope">
              {{ idTypeDisplay(scope.row.idType) }}
            </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">
                  <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-IdTypeConfig-Update'].show"
                      :command="{ type: 2, row: scope.row }"
                    >
                      <el-icon><Edit /></el-icon>
                      {{ t('R-IdTypeConfig-Update') }}
                    </el-dropdown-item>
                    <el-dropdown-item
                      v-if="display['R-IdTypeConfig-Delete'].show"
                      :command="{ type: 1, row: scope.row }"
                    >
                      <el-icon><Delete /></el-icon>
                      {{ t('R-IdTypeConfig-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-if="approvalAllDialog"
      v-model="approvalAllDialog"
      :title="t('R-IdTypeConfig')"
      :rules="rules"
      width="600px"
    >
      <el-form
        ref="dialogFormRef"
        :rules="rules"
        :model="form"
        label-width="130px"
        label-position="right"
        class="business-edit-form"
      >
        <el-form-item prop="country" :label="t('card.Form.f7')">
          <el-select
            v-model="form.country"
            multiple
            :disabled="type == 2"
            :placeholder="t('card.vaildate.v6')"
          >
            <el-option
              v-for="item in countryCityList"
              :key="item.id"
              :label="lang == 'cn' ? item.cnName : item.enName"
              :value="item.code"
            />
          </el-select>
        </el-form-item>

        <el-form-item prop="idType" :label="t('card.Form.f16')">
          <el-select v-model="form.idType" multiple :placeholder="t('card.vaildate.v14')">
            <el-option
              v-for="(item, index) in idTypeList"
              :key="index"
              :label="t(item.name)"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="approvalAllDialog = false">
            {{ t('Ucard.Business.p32') }}
          </el-button>
          <el-button type="primary" @click="idTypesConfigAdd">
            {{ t('card.Btn.Confirm') }}
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
  import { ref, reactive, computed, onMounted, watch, inject } from 'vue'
  import { useI18n } from 'vue-i18n'
  import { ElMessage, ElMessageBox } from 'element-plus'
  import Service from '@/service/ucard'
  import Config from '@/config/index'
  import PagePagination from '@/components/pagePagination'
  import { idTypeFilterOptions, idTypeList } from '@/views/card/CardIdTypeConfig/const'
  import { Delete, Edit, Search } from '@element-plus/icons-vue'

  const { t } = useI18n()
  const { Code } = Config

  // 使用 inject 获取 session
  const Session = inject('session')

  // Refs
  const formRef = ref(null)
  const dialogFormRef = ref(null)
  const pictLoading = ref(false)
  const approvalAllDialog = ref(false)
  const type = ref(1)
  const multipleSelection = ref([])
  const countryCityList = ref([])

  // Reactive data
  const search = reactive({
    idType: '',
    code: '',
  })

  const mock_tableData = ref([])

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

  const form = reactive({
    country: null,
    idType: null,
  })

  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 lang = computed(() => Session?.Get('lang') || 'cn')

  // Methods
  const getCountryListForSelect = async () => {
    const res = await Service.ucardCountryCity({ code: '' })
    if (res.code === 200 || res.code === 0) {
      countryCityList.value = res.data || []
    }
  }

  const idTypeDisplay = (idTypeStr) => {
    const types = idTypeStr.split(',').map((t) => t.trim())
    return idTypeList
      .filter((item) => types.includes(item.value))
      .map((item) => t(item.name))
      .join(',')
  }

  const handleCommand = (command) => {
    switch (command.type) {
      case 1:
        multipleSelection.value = [command.row.id]
        deleteAll()
        break
      case 2: {
        const idType = command.row.idType.split(',').map((item) => item.trim())
        const country = [command.row.code]
        Object.assign(form, {
          ...command.row,
          country,
          idType,
        })
        approvalAll(2)
        break
      }
    }
  }

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

  const approvalAll = (approvalType) => {
    type.value = approvalType
    if (approvalType == 1) {
      Object.assign(form, {
        country: null,
        idType: null,
      })
    }
    approvalAllDialog.value = true
  }

  //批量删除
  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.idTypesConfigDelete({
        ids: multipleSelection.value,
      })
      if (res.code == Code.StatusOK) {
        ElMessage.success(t('Msg.DeleteSuccess'))
        searchFunc()
      } else {
        ElMessage.error(res.msg)
      }
    } catch (error) {
      // 用户取消删除
    }
  }

  // 添加
  const idTypesConfigAdd = async () => {
    try {
      const valid = await dialogFormRef?.value.validate()
      if (!valid) return

      const result = countryCityList.value
        .filter((item) => form.country.includes(item.code))
        .map((item) => {
          return {
            enName: item.enName,
            cnName: item.cnName,
            code: item.code,
            idType: form.idType.join(','),
          }
        })

      const res = await Service.idTypesConfigAdd(result)
      if (res.code == 200) {
        Object.assign(form, {
          country: null,
          idType: null,
        })
        approvalAllDialog.value = false
        toSearch()
      } else {
        ElMessage.error(res.msg)
      }
    } catch (error) {
      console.log(error)
    }
  }

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

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

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

    const res = await Service.idTypesConfigList({
      ...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()
  }

  onMounted(() => {
    searchFunc()
    getCountryListForSelect()
  })
</script>

<style scoped lang="scss">
  #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 {
        width: 400px;
      }
    }
  }
</style>
