<template>
  <div
    id="div-content"
    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>
              <el-input
                v-model.trim="search.merchantName"
                class="crm-border-radius-no"
                clearable
                :placeholder="`${t('Placeholder.Input')}${t('ShopManage.t1')}`"
                @keyup.enter="toSearch"
              >
              </el-input>
            </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 v-if="display['R-Role-Add'].show">
          <div class="search_action_btn">
            <span class="crm-cursor" @click="handleAdd">
              <el-icon><Plus /></el-icon>
              <span>{{ $t('Btn.Add') }}</span>
            </span>
          </div>
        </el-form-item>
      </el-form>
    </div>
    <el-table :data="tableData" stripe style="width: 100%">
      <el-table-column prop="merchantName" align="left" :label="t('ShopManage.t1')">
        <template #default="scope">
          {{ scope.row.merchantName || '--' }}
        </template>
      </el-table-column>
      <el-table-column prop="name" align="left" :label="t('Label.Name')">
        <template #default="{ row }">
          <span v-if="row.firstName">
            {{ row.firstName + ' ' }}
          </span>
          <span v-if="row.lastName">{{ row.lastName }}</span>
          <span v-if="!row.firstName && !row.lastName">
            {{ '--' }}
          </span>
        </template>
      </el-table-column>
      <el-table-column prop="email" align="left" :label="t('ShopManage.t2')">
        <template #default="scope">
          {{ scope.row.email || '--' }}
        </template>
      </el-table-column>
      <el-table-column prop="mobile" align="left" :label="t('ShopManage.t3')">
        <template #default="scope">
          {{ scope.row.mobile || '--' }}
        </template>
      </el-table-column>
      <el-table-column prop="country" align="left" :label="t('ShopManage.t4')">
        <template #default="scope">
          {{ isZhCn ? scope.row.countryName : scope.row.countryEnName || '--' }}
        </template>
      </el-table-column>
      <el-table-column prop="address" align="left" :label="t('ShopManage.t5')">
        <template #default="scope">
          {{ scope.row.address || '--' }}
        </template>
      </el-table-column>
      <el-table-column prop="opt" 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-Role-Update'].show"
                  :command="{ type: 'editor', row: scope.row }"
                >
                  <el-icon><Edit /></el-icon>
                  <span>{{ $t('Btn.Editor') }}</span>
                </el-dropdown-item>
                <el-dropdown-item
                  v-if="display['R-Role-Delete'].show"
                  :command="{ type: 'delete', id: scope.row.id }"
                >
                  <el-icon><Delete /></el-icon>
                  <span>{{ $t('Btn.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="dialogVisible"
      :title="t(isEdit ? 'ShopManage.edit' : 'ShopManage.add')"
      width="500px"
      :close-on-click-modal="false"
      @close="onClose"
    >
      <el-form ref="addFormRef" :model="addForm" :rules="formRules" label-width="120px">
        <el-form-item :label="`${t('ShopManage.t1')}:`" prop="merchantName">
          <el-input v-model.trim="addForm.merchantName" :placeholder="t('Placeholder.Input')">
          </el-input>
        </el-form-item>
        <el-form-item :label="`${t('ShopManage.t7')}:`" prop="firstName">
          <el-input v-model.trim="addForm.firstName" :placeholder="t('Placeholder.Input')">
          </el-input>
        </el-form-item>
        <el-form-item :label="`${t('ShopManage.t6')}:`" prop="lastName">
          <el-input v-model.trim="addForm.lastName" :placeholder="t('Placeholder.Input')">
          </el-input>
        </el-form-item>
        <el-form-item :label="`${t('ShopManage.t2')}:`" prop="email">
          <el-input v-model.trim="addForm.email" :placeholder="t('Placeholder.Input')"> </el-input>
        </el-form-item>
        <el-form-item :label="`${t('ShopManage.t3')}:`" prop="mobile">
          <el-input v-model.trim="addForm.mobile" :placeholder="t('Placeholder.Input')"> </el-input>
        </el-form-item>
        <el-form-item :label="`${t('ShopManage.t4')}:`" prop="country">
          <el-select
            v-model="addForm.country"
            :placeholder="t('Placeholder.Choose')"
            clearable
            filterable
          >
            <el-option
              v-for="(item, index) in country"
              :key="index"
              :label="item.enName"
              :value="item.code"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item :label="`${t('ShopManage.t5')}:`" prop="address">
          <el-input v-model.trim="addForm.address" :placeholder="t('Placeholder.Input')">
          </el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">{{ t('Btn.Cancel') }} </el-button>
          <el-button type="primary" :loading="addLoading" @click="handleConfirm"
            >{{ t('Btn.Confirm') }}
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>
<script setup lang="ts">
  import { Delete, Edit, Plus, Search } from '@element-plus/icons-vue'
  import { computed, inject, onMounted, reactive, ref } from 'vue'
  import PagePagination from '@/components/pagePagination/index.vue'
  import Service from '@/service/user'
  import { useI18n } from 'vue-i18n'
  import Config from '@/config'
  import { ElMessageBox } from 'element-plus'
  import ServiceMarket from '@/service/marketing'
  import store from '@/vuexStore'

  const { Code, Pattern } = Config
  const Session = inject('session')
  const pigeon = inject('pigeon')
  const { t } = useI18n()
  const tableData = ref([])
  const dialogVisible = ref(false)
  const isEdit = ref(false)
  const addLoading = ref(false)
  const formRef = ref(null)
  const addFormRef = ref(null)
  const addForm = reactive({})
  const country = ref(null)
  // reactive 响应式对象
  const search = reactive({
    merchantName: '',
  })

  const pictLoading = ref(false)
  // computed 计算属性
  const display = computed(() => {
    const displayData = Session.Get('display', true)
    return displayData ? JSON.parse(displayData) : {}
  })
  const isZhCn = computed(() => store.state.home.isZhCn)

  const formRules = computed(() => ({
    merchantName: [
      {
        required: true,
        message: t('ShopManage.p1'),
        trigger: 'blur',
      },
    ],
    email: [
      {
        required: true,
        validator: (rule, value, callback) => {
          if (value) {
            const test = Pattern.Email.test(value)
            if (test) {
              return callback()
            } else {
              return callback(new Error(t('vaildate.email.format')))
            }
          } else {
            return callback(new Error(t('vaildate.email.empty')))
          }
        },
        trigger: 'blur',
      },
    ],
    mobile: [
      {
        required: true,
        message: t('ShopManage.p3'),
        trigger: 'blur',
      },
    ],
    country: [
      {
        required: true,
        message: t('ShopManage.p4'),
        trigger: 'change',
      },
    ],
    address: [
      {
        required: true,
        message: t('ShopManage.p5'),
        trigger: 'blur',
      },
    ],
    lastName: [
      {
        required: true,
        message: t('ShopManage.p6'),
        trigger: 'blur',
      },
    ],
    firstName: [
      {
        required: true,
        message: t('ShopManage.p7'),
        trigger: 'blur',
      },
    ],
  }))
  const pagerInfo = reactive({
    row: 10,
    current: 1,
    pageTotal: 0,
    rowTotal: 0,
  })
  const searchFunc = async () => {
    pictLoading.value = true

    if (!display.value['R-ShopManage-Page']?.show) {
      pigeon.MessageWarning(t('Msg.NotDisplay'))
      pictLoading.value = false
      return
    }

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

      if (res.code == Code.StatusOK) {
        console.log(res)
        tableData.value = res.data
        if (res.page != null) {
          pagerInfo.rowTotal = res.page.rowTotal
          pagerInfo.pageTotal = res.page.pageTotal
        } else {
          pagerInfo.rowTotal = 0
        }
        pigeon.MessageOK(t('Msg.SearchSuccess'))
      } else {
        pigeon.MessageError(res.msg)
      }
    } catch (error) {
      console.log(error)
    } finally {
      pictLoading.value = false
    }
  }

  const toSearch = () => {
    pagerInfo.current = 1
    searchFunc()
  }
  // 获取国家列表
  const getCountry = async () => {
    try {
      let res = await ServiceMarket.Country({})
      if (res.code == Code.StatusOK) {
        country.value = res.data
      } else {
        pigeon.MessageError(res.msg || t('Msg.Error'))
      }
    } catch (error) {
      console.error('获取国家列表失败:', error)
      pigeon.MessageError(t('Msg.NetworkError'))
    }
  }
  const handleAdd = () => {
    Object.keys(addForm).forEach((key) => delete addForm[key])
    isEdit.value = false
    dialogVisible.value = true
  }
  const onClose = () => {
    addFormRef.value?.resetFields()
  }
  const handleConfirm = async () => {
    const valid = await addFormRef.value.validate()
    if (!valid) return
    addLoading.value = true
    try {
      const params = { ...addForm }
      const res = isEdit.value
        ? await Service.shopManageEdit(params)
        : await Service.shopManageAdd(params)
      if (res.code == Code.StatusOK) {
        dialogVisible.value = false
        searchFunc()
      } else {
        pigeon.MessageError(res.msg)
      }
      onClose()
      addLoading.value = false
    } catch (error) {
      console.error(error)
    }
  }

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

  const handleCurrentChange = (val) => {
    pagerInfo.current = val
    searchFunc()
  }
  // 删除
  const handleDelete = async (id) => {
    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.shopManageDel({ id })
      if (res.code == Code.StatusOK) {
        pigeon.success(t('Msg.DeleteSuccess'))
        searchFunc() // 刷新列表
      } else {
        pigeon.MessageError(res.msg)
      }
    } catch (error) {
      console.log(error)
    }
  }
  // 处理下拉菜单命令
  const handleCommand = (command) => {
    if (command.type === 'editor') {
      Object.assign(addForm, command.row)
      isEdit.value = true
      dialogVisible.value = true
    } else if (command.type === 'delete') {
      console.log(command.id)
      handleDelete(command.id)
    }
  }

  // 挂载生命周期
  onMounted(() => {
    searchFunc()
    getCountry()
  })
</script>

<style scoped lang="scss">
  #div-content {
    .dialog_header_w {
      .crm_search_down {
        width: 400px;
      }
    }
  }
</style>
