<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>
              <el-select
                v-model="search.tag"
                :placeholder="$t('Placeholder.Choose')"
                class="crm_search_down crm-border-radius-no"
              >
                <el-option
                  v-for="item in tagOptions"
                  :key="item.value"
                  :label="t(item.label)"
                  :value="item.value"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-input
                v-if="search.tag == 1"
                v-model.trim="search.cIdRegexp"
                :placeholder="$t('Placeholder.Input')"
                class="crm-border-left-no crm-border-radius-no"
                clearable
                @keyup.enter="toSearch"
              ></el-input>
              <el-select
                v-if="search.tag == 2"
                v-model="search.enableStatus"
                :placeholder="$t('Placeholder.Choose')"
                class="crm-border-left-no crm-border-radius-no"
                clearable
                @change="toSearch"
              >
                <el-option
                  v-for="item in enableStatusOptions"
                  :key="item.value"
                  :label="t(item.label)"
                  :value="item.value"
                ></el-option>
              </el-select>
              <!-- 邮箱 -->
              <el-input
                v-if="search.tag == 3"
                v-model.trim="search.cIdRegexp"
                :placeholder="$t('Placeholder.Input')"
                class="crm-border-left-no crm-border-radius-no"
                clearable
                @keyup.enter="toSearch"
              ></el-input>
              <!-- 手机号 -->
              <el-input
                v-if="search.tag == 4"
                v-model.trim="search.cIdRegexp"
                :placeholder="$t('Placeholder.Input')"
                class="crm-border-left-no crm-border-radius-no"
                clearable
                @keyup.enter="toSearch"
              ></el-input>
            </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-UserRights-Add'].show">
          <div class="search_action_btn">
            <span class="crm-cursor delete active" @click="approvalAll">
              {{ $t('R-UserRights-Add') }}
            </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"
            :selectable="checkSelectable"
          >
          </el-table-column> -->

          <el-table-column :label="$t('card.Info.t21')" align="left" prop="cIdRegexp" />
          <!-- <el-table-column
            prop="addTime"
            align="left"
            :label="$t('Ucard.Recharge.item9')"
          /> -->
          <!-- 手机号 -->
          <el-table-column :label="$t('card.Info.t30')" align="left" prop="phoneRegexp" />
          <!-- 邮箱 -->
          <el-table-column :label="$t('card.Info.t29')" align="left" prop="emailRegexp" />
          <el-table-column
            :label="$t('Apply_info.AddressInfo.Country')"
            align="left"
            prop="emailRegexp"
          >
            <template #default="scope">
              {{ lang == 'cn' ? scope.row.countryNames : scope.row.countryEnNames }}
            </template>
          </el-table-column>
          <el-table-column
            :label="$t('Apply_info.AddressInfo.Region')"
            align="left"
            prop="emailRegexp"
          >
            <template #default="scope">
              {{ lang == 'cn' ? scope.row.stateNames : scope.row.stateEnNames }}
            </template>
          </el-table-column>
          <el-table-column
            :label="$t('Apply_info.AddressInfo.City')"
            align="left"
            prop="emailRegexp"
          >
            <template #default="scope">
              {{ lang == 'cn' ? scope.row.cityNames : scope.row.cityEnNames }}
            </template>
          </el-table-column>
          <el-table-column :label="$t('card.Info.t23')" align="left" prop="addTime" />
          <el-table-column :label="$t('card.Info.t22')" align="left" prop="enableStatus">
            <template #default="scope">
              <el-switch
                v-model="scope.row.enableStatus"
                :active-text="$t('Documentary.tradingCenter.item46')"
                :active-value="1"
                :inactive-text="$t('Documentary.tradingCenter.item47')"
                :inactive-value="0"
                active-color="#368FEC"
                class="crm_switch"
                inactive-color="#EB3F57"
                @change="selectChange(scope.row)"
              >
              </el-switch>
            </template>
          </el-table-column>
          <el-table-column :label="$t('Label.Action')" align="center" prop="opt">
            <template #default="scope">
              <el-dropdown trigger="click" @command="handleCommand">
                <span class="el-dropdown-link crm-cursor">
                  <i class="iconfont iconcaidan" style="font-weight: bold; font-size: 20px"></i>
                </span>
                <template #dropdown>
                  <el-dropdown-menu>
                    <el-dropdown-item
                      v-if="display['R-UserRights-Delete'].show"
                      :command="{ type: 1, row: scope.row }"
                    >
                      <el-icon><Delete /></el-icon>
                      {{ $t('R-UserRights-Delete') }}
                    </el-dropdown-item>
                  </el-dropdown-menu>
                </template>
              </el-dropdown>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>
    <PagePagination
      :pager-info="pagerInfo"
      @current-change="handleCurrentChange"
      @size-change="handleSizeChange"
    />
    <el-dialog
      v-if="approvalAllDialog"
      v-model="approvalAllDialog"
      :rules="rules"
      :title="$t('card.Info.t26')"
      width="600px"
    >
      <el-form
        :model="form"
        :rules="rules"
        class="business-edit-form"
        label-position="right"
        label-width="150px"
      >
        <el-form-item :label="$t('card.Info.t21') + '：'" prop="cIdRegexp">
          <el-input v-model="form.cIdRegexp" :placeholder="$t('Placeholder.Input')"></el-input>
        </el-form-item>
        <el-form-item :label="t('card.Info.t29') + '：'" prop="emailRegexp">
          <el-input v-model="form.emailRegexp" :placeholder="$t('Placeholder.Input')"></el-input>
        </el-form-item>
        <el-form-item :label="$t('card.Info.t30') + '：'" prop="phoneRegexp">
          <el-input v-model="form.phoneRegexp" :placeholder="$t('Placeholder.Input')"></el-input>
        </el-form-item>
        <el-form-item :label="$t('card.Info.t31') + '：'" prop="areaList">
          <el-cascader
            v-model="form.areaList"
            class="crm_search_down width-100"
            :show-all-levels="false"
            :options="options"
            filterable
            :placeholder="$t('Placeholder.Choose')"
            :props="cascaderProps"
            clearable
          ></el-cascader>
        </el-form-item>
        <el-form-item :label="$t('card.Info.t22') + '：'" class="crm_switch" prop="enableStatus">
          <el-switch
            v-model="form.enableStatus"
            :active-text="$t('Documentary.tradingCenter.item46')"
            :active-value="1"
            :inactive-text="$t('Documentary.tradingCenter.item47')"
            :inactive-value="0"
            active-color="#368FEC"
            class="crm_switch"
            inactive-color="#EB3F57"
          >
          </el-switch>
        </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="permissionAdd">
            {{ $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 PagePagination from '@/components/pagePagination'
  import Service from '@/service/ucard'
  import Config from '@/config/index'
  import { enableStatusOptions, tagOptions } from '@/views/card/CardUserRights/const'
  import { Search, Delete } from '@element-plus/icons-vue'

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

  // Refs
  const formRef = ref(null)
  const pictLoading = ref(false)
  const approvalAllDialog = ref(false)
  const multipleSelection = ref([])

  // Reactive data
  const search = reactive({
    tag: 1,
    enableStatus: '',
    cIdRegexp: '',
    emailRegexp: '',
    phoneRegexp: '',
  })

  const mock_tableData = ref([])

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

  const form = reactive({
    cIdRegexp: null,
    enableStatus: 1,
    emailRegexp: null,
    phoneRegexp: null,
    areaList: null,
  })

  const options = ref([])

  const rules = reactive({
    enableStatus: [
      {
        required: true,
        message: t('vaildate.select.empty'),
        trigger: 'blur',
      },
    ],
    cIdRegexp: [
      {
        message: t('vaildate.input.empty'),
        trigger: 'blur',
      },
    ],
    emailRegexp: [
      {
        message: t('vaildate.input.empty'),
        trigger: 'blur',
      },
    ],
    phoneRegexp: [
      {
        message: t('vaildate.input.empty'),
        trigger: 'blur',
      },
    ],
  })

  const lang = computed(() => Session.Get('lang') || 'cn')
  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 cascaderProps = reactive({
    multiple: true,
    checkStrictly: true,
    lazy: true,
    async lazyLoad(node, resolve) {
      const { value } = node
      const pid = value ? value.split(',')[0] : ''

      try {
        const res = await Service.countryGet({ pid })
        if (res.code == Code.StatusOK) {
          const nodes = res.data.map((item) => {
            const name = lang.value == 'cn' ? item.name : item.enName
            return {
              id: item.id,
              label: name,
              value: `${item.id},${item.name},${item.enName},${item.code ?? ''}`,
              leaf: item.leaf,
            }
          })
          resolve(nodes)
        } else {
          resolve([])
        }
      } catch (error) {
        console.error('加载地区数据失败:', error)
        resolve([])
      }
    },
  })

  // Methods
  const handleCommand = (command) => {
    if (command.type == 1) {
      ElMessageBox.confirm(t('card.Msg.m14'), t('card.Msg.m13'), {
        confirmButtonText: t('card.Btn.Confirm'),
        cancelButtonText: t('card.Btn.Cancel'),
        type: 'warning',
      }).then(async () => {
        const res = await Service.permissionDelete({
          id: command.row.id,
          cId: user.value.cId,
        })
        if (res.code == 200) {
          ElMessage.success(t('Msg.DeleteSuccess'))
          toSearch()
        } else {
          ElMessage.error(res.msg)
        }
      })
    }
  }

  const selectChange = async (val) => {
    try {
      const res = await Service.permissionUpdate({
        id: val.id,
        enableStatus: val.enableStatus,
        cId: user.value.cId,
      })
      if (res.code == 200) {
        ElMessage.success(t('card.Info.t27'))
        searchFunc()
      } else {
        ElMessage.error(res.msg)
      }
    } catch (error) {
      ElMessage.error(t('Msg.SystemError'))
    }
  }

  //选择多项
  const handleSelectionChange = (val) => {
    multipleSelection.value = []
    val.forEach((item) => {
      if (item.approveStatus == '2' || item.approveStatus == '3') return
      multipleSelection.value.push(item.id)
    })
  }

  const checkSelectable = (row) => {
    return row.approveStatus == '1'
  }

  const approvalAll = () => {
    approvalAllDialog.value = true
  }

  // 添加
  const permissionAdd = async () => {
    const { cIdRegexp, enableStatus, emailRegexp, phoneRegexp, areaList } = form

    let countryEnNames = []
    let stateEnNames = []
    let countryCodes = []
    let cityEnNames = []
    let countryNames = []
    let stateNames = []
    let cityNames = []

    if (areaList && areaList.length) {
      // 地区数据处理
      areaList.forEach((item) => {
        if (item && item.length) {
          item.forEach((child, childIndex) => {
            if (child) {
              const items = child.split(',')
              // 0 id 1 name 2 enname 3 code 国家有，别的没有
              if (childIndex === 0) {
                countryNames.push(items[1] ?? '')
                countryEnNames.push(items[2] ?? '')
                countryCodes.push(items[3] ?? '')
              } else if (childIndex === 1) {
                stateNames.push(items[1] ?? '')
                stateEnNames.push(items[2] ?? '')
              } else {
                cityNames.push(items[1] ?? '')
                cityEnNames.push(items[2] ?? '')
              }
            }
          })
        }
      })
    }

    const params = {
      cId: user.value.cId,
      cIdRegexp,
      enableStatus,
      emailRegexp,
      phoneRegexp,
      countryEnNames: [...new Set(countryEnNames)].join(','),
      countryCodes: [...new Set(countryCodes)].join(','),
      stateEnNames: [...new Set(stateEnNames)].join(','),
      cityEnNames: [...new Set(cityEnNames)].join(','),
      countryNames: [...new Set(countryNames)].join(','),
      stateNames: [...new Set(stateNames)].join(','),
      cityNames: [...new Set(cityNames)].join(','),
    }

    const res = await Service.permissionAdd(params)
    if (res.code == 200) {
      Object.assign(form, {
        cIdRegexp: null,
        enableStatus: 1,
        approveStatus: null,
        emailRegexp: null,
        phoneRegexp: null,
        areaList: null,
      })
      approvalAllDialog.value = false
      ElMessage.success(t('card.Info.t28'))
      toSearch()
    } else {
      ElMessage.error(res.msg)
    }
  }

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

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

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

    const res = await Service.permissionPage({
      ...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 getCountry = async () => {
    const res = await Service.countryGet({})
    if (res.code == Code.StatusOK) {
      options.value = res.data.map((item) => {
        const name = lang.value == 'cn' ? item.name : item.enName
        return {
          id: item.id,
          label: name,
          value: `${item.id},${item.name},${item.enName},${item.code ?? ''}`,
        }
      })
    } else {
      ElMessage.error(res.msg)
    }
  }

  // Lifecycle hooks
  onMounted(() => {
    searchFunc()
    getCountry()
  })

  // Watchers
  watch(
    () => search.tag,
    () => {
      search.cIdRegexp = ''
      search.enableStatus = ''
      search.emailRegexp = ''
      search.phoneRegexp = ''
    }
  )
</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 {
        width: 400px;
      }
    }
    .width-100 {
      width: 100% !important;
    }
  }
</style>
