<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="mb-[10px]">
        <el-card shadow="hover">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true" label-width="150px">
            <!--            <el-form-item label="用户ID" prop="userId">-->
            <!--              <el-input v-model="queryParams.userId" placeholder="请输入所属用户ID" clearable @keyup.enter="handleQuery" />-->
            <!--            </el-form-item>-->
            <!--            <el-form-item label="领星ID" prop="sid">-->
            <!--              <el-input v-model="queryParams.sid" placeholder="请输入领星ERP店铺标识ID" clearable @keyup.enter="handleQuery" />-->
            <!--            </el-form-item>-->
            <!--            <el-form-item label="站点ID" prop="mid">-->
            <!--              <el-input v-model="queryParams.mid" placeholder="请输入站点ID" clearable @keyup.enter="handleQuery" />-->
            <!--            </el-form-item>-->
            <el-form-item label="店铺名称" prop="storeName">
              <el-input v-model="queryParams.storeName" placeholder="请输入店铺名称" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="亚马逊店铺ID" prop="sellerId">
              <el-input v-model="queryParams.sellerId" placeholder="请输入亚马逊店铺ID" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <!--            <el-form-item label="店铺账户" prop="accountName">-->
            <!--              <el-input v-model="queryParams.accountName" placeholder="请输入店铺账户名称" clearable @keyup.enter="handleQuery" />-->
            <!--            </el-form-item>-->
            <!--            <el-form-item label="店铺ID" prop="sellerAccountId">-->
            <!--              <el-input v-model="queryParams.sellerAccountId" placeholder="请输入店铺账号ID" clearable @keyup.enter="handleQuery" />-->
            <!--            </el-form-item>-->
            <!--            <el-form-item label="站点简称" prop="region">-->
            <!--              <el-input v-model="queryParams.region" placeholder="请输入站点简称" clearable @keyup.enter="handleQuery" />-->
            <!--            </el-form-item>-->
            <!--            <el-form-item label="商城国家" prop="country">-->
            <!--              <el-input v-model="queryParams.country" placeholder="请输入商城所在国家" clearable @keyup.enter="handleQuery" />-->
            <!--            </el-form-item>-->
            <!--            <el-form-item label="市场ID" prop="marketplaceId">-->
            <!--              <el-input v-model="queryParams.marketplaceId" placeholder="请输入亚马逊市场ID" clearable @keyup.enter="handleQuery" />-->
            <!--            </el-form-item>-->
            <!--            <el-form-item label="广告授权" prop="hasAdsSetting">-->
            <!--              <el-input v-model="queryParams.hasAdsSetting" placeholder="请输入广告授权 0未授权 1已授权" clearable @keyup.enter="handleQuery" />-->
            <!--            </el-form-item>-->
            <el-form-item>
              <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </transition>

    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['amz:amazonStore:add']">新增 </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate()" v-hasPermi="['amz:amazonStore:edit']"
              >修改
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete()" v-hasPermi="['amz:amazonStore:remove']"
              >删除
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="warning" plain icon="Download" @click="handleExport" v-hasPermi="['amz:amazonStore:export']">导出 </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="warning" plain icon="Download" @click="collectAmzStore" v-hasPermi="['amz:amazonStore:export']">获取店铺数据 </el-button>
          </el-col>
          <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>
      </template>

      <el-table v-loading="loading" :data="amazonStoreList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="店铺名称" align="center" prop="storeName" />
        <el-table-column label="用户名称" align="center" prop="nickName" />
        <el-table-column label="登录名" align="center" prop="userName" />
        <el-table-column label="领星ERP店铺标识ID" align="center" prop="sid" />
        <el-table-column label="所属用户ID" align="center" prop="userId" />
        <el-table-column label="站点ID" align="center" prop="mid" />
        <el-table-column label="亚马逊店铺ID" align="center" prop="sellerId" />
        <el-table-column label="店铺账户名称" align="center" prop="accountName" />
        <el-table-column label="店铺账号ID" align="center" prop="sellerAccountId" />
        <el-table-column label="站点简称" align="center" prop="region" />
        <el-table-column label="商城所在国家" align="center" prop="country" />
        <el-table-column label="亚马逊市场ID" align="center" prop="marketplaceId" />
        <el-table-column label="广告授权 0未授权 1已授权" align="center" prop="hasAdsSetting" />
        <el-table-column label="店铺状态 0停用 1正常 2异常 3欠费" align="center" prop="status" />
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-tooltip content="修改" placement="top">
              <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['amz:amazonStore:edit']"></el-button>
            </el-tooltip>
            <el-tooltip content="指定运营" placement="top">
              <el-button link type="primary" icon="Avatar" @click="changeUser(scope.row)" v-hasPermi="['amz:amazonStore:edit']"></el-button>
            </el-tooltip>
            <el-tooltip content="删除" placement="top">
              <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['amz:amazonStore:remove']"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" @pagination="getList" />
    </el-card>
    <!-- 添加或修改亚马逊店铺信息对话框 -->
    <el-dialog :title="dialog.title" v-model="dialog.visible" width="500px" append-to-body>
      <el-form ref="amazonStoreFormRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="所属用户ID" prop="userId">
          <el-input v-model="form.userId" placeholder="请输入所属用户ID" />
        </el-form-item>
        <el-form-item label="领星ERP店铺标识ID" prop="sid">
          <el-input v-model="form.sid" placeholder="请输入领星ERP店铺标识ID" />
        </el-form-item>
        <el-form-item label="站点ID" prop="mid">
          <el-input v-model="form.mid" placeholder="请输入站点ID" />
        </el-form-item>
        <el-form-item label="店铺名称" prop="storeName">
          <el-input v-model="form.storeName" placeholder="请输入店铺名称" />
        </el-form-item>
        <el-form-item label="亚马逊店铺ID" prop="sellerId">
          <el-input v-model="form.sellerId" placeholder="请输入亚马逊店铺ID" />
        </el-form-item>
        <el-form-item label="店铺账户名称" prop="accountName">
          <el-input v-model="form.accountName" placeholder="请输入店铺账户名称" />
        </el-form-item>
        <el-form-item label="店铺账号ID" prop="sellerAccountId">
          <el-input v-model="form.sellerAccountId" placeholder="请输入店铺账号ID" />
        </el-form-item>
        <el-form-item label="站点简称" prop="region">
          <el-input v-model="form.region" placeholder="请输入站点简称" />
        </el-form-item>
        <el-form-item label="商城所在国家" prop="country">
          <el-input v-model="form.country" placeholder="请输入商城所在国家" />
        </el-form-item>
        <el-form-item label="亚马逊市场ID" prop="marketplaceId">
          <el-input v-model="form.marketplaceId" placeholder="请输入亚马逊市场ID" />
        </el-form-item>
        <el-form-item label="广告授权 0未授权 1已授权" prop="hasAdsSetting">
          <el-input v-model="form.hasAdsSetting" placeholder="请输入广告授权 0未授权 1已授权" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <assign-user ref="selectRef" :store-data="form.id" :role-id="yunyingRoleId" @ok="handleQuery" />
  </div>
</template>

<script setup name="AmazonStore" lang="ts">
import { listAmazonStore, getAmazonStore, delAmazonStore, addAmazonStore, updateAmazonStore, collectAmzStoreData } from '@/api/amz/amazonStore';
import { AmazonStoreVO, AmazonStoreQuery, AmazonStoreForm } from '@/api/amz/amazonStore/types';
import AssignUser from '@/views/amz/amazonStore/assignUser.vue';
import { getInquiryRequest } from '@/api/amz/inquiryRequest';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;

const amazonStoreList = ref<AmazonStoreVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const yunyingRoleId = ref(4);

const selectRef = ref<InstanceType<typeof AssignUser>>();

const queryFormRef = ref<ElFormInstance>();
const amazonStoreFormRef = ref<ElFormInstance>();

const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

const initFormData: AmazonStoreForm = {
  id: undefined,
  userId: undefined,
  sid: undefined,
  mid: undefined,
  storeName: undefined,
  sellerId: undefined,
  accountName: undefined,
  sellerAccountId: undefined,
  region: undefined,
  country: undefined,
  marketplaceId: undefined,
  hasAdsSetting: undefined,
  status: undefined
};
const data = reactive<PageData<AmazonStoreForm, AmazonStoreQuery>>({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    userId: undefined,
    sid: undefined,
    mid: undefined,
    storeName: undefined,
    sellerId: undefined,
    accountName: undefined,
    sellerAccountId: undefined,
    region: undefined,
    country: undefined,
    marketplaceId: undefined,
    hasAdsSetting: undefined,
    status: undefined,
    params: {}
  },
  rules: {
    id: [{ required: true, message: '主键ID不能为空', trigger: 'blur' }],
    userId: [{ required: true, message: '所属用户ID不能为空', trigger: 'blur' }],
    sid: [{ required: true, message: '领星ERP店铺标识ID不能为空', trigger: 'blur' }],
    mid: [{ required: true, message: '站点ID不能为空', trigger: 'blur' }],
    storeName: [{ required: true, message: '店铺名称不能为空', trigger: 'blur' }],
    sellerId: [{ required: true, message: '亚马逊店铺ID不能为空', trigger: 'blur' }],
    accountName: [{ required: true, message: '店铺账户名称不能为空', trigger: 'blur' }],
    sellerAccountId: [{ required: true, message: '店铺账号ID不能为空', trigger: 'blur' }],
    region: [{ required: true, message: '站点简称不能为空', trigger: 'blur' }],
    country: [{ required: true, message: '商城所在国家不能为空', trigger: 'blur' }],
    marketplaceId: [{ required: true, message: '亚马逊市场ID不能为空', trigger: 'blur' }],
    hasAdsSetting: [{ required: true, message: '广告授权 0未授权 1已授权不能为空', trigger: 'blur' }],
    status: [{ required: true, message: '店铺状态 0停用 1正常 2异常 3欠费不能为空', trigger: 'change' }]
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询亚马逊店铺信息列表 */
const getList = async () => {
  loading.value = true;
  const res = await listAmazonStore(queryParams.value);
  amazonStoreList.value = res.rows;
  total.value = res.total;
  loading.value = false;
};

/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
};

/** 表单重置 */
const reset = () => {
  form.value = { ...initFormData };
  amazonStoreFormRef.value?.resetFields();
};

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
};

const collectAmzStore = async () => {
  loading.value = true;
  const res = await collectAmzStoreData();
  loading.value = false;
};

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
};

/** 多选框选中数据 */
const handleSelectionChange = (selection: AmazonStoreVO[]) => {
  ids.value = selection.map((item) => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
};

/** 新增按钮操作 */
const handleAdd = () => {
  reset();
  dialog.visible = true;
  dialog.title = '添加亚马逊店铺信息';
};

/** 修改按钮操作 */
const handleUpdate = async (row?: AmazonStoreVO) => {
  reset();
  const _id = row?.id || ids.value[0];
  form.value.id = _id;
  console.log('form.value.id', _id);
  const res = await getInquiryRequest(_id);
  Object.assign(form.value, res.data);
  dialog.visible = true;
  dialog.title = '修改亚马逊店铺信息';
};

const changeUser = async (row?: AmazonStoreVO) => {
  reset();
  const _id = row?.id || ids.value[0];
  form.value.id = _id;
  console.log('form.value.id', _id);
  selectRef.value?.show();
  // dialog.visible = true;
  // dialog.title = '修改亚马逊店铺信息';
};

/** 提交按钮 */
const submitForm = () => {
  amazonStoreFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      if (form.value.id) {
        await updateAmazonStore(form.value).finally(() => (buttonLoading.value = false));
      } else {
        await addAmazonStore(form.value).finally(() => (buttonLoading.value = false));
      }
      proxy?.$modal.msgSuccess('操作成功');
      dialog.visible = false;
      await getList();
    }
  });
};

/** 删除按钮操作 */
const handleDelete = async (row?: AmazonStoreVO) => {
  const _ids = row?.id || ids.value;
  await proxy?.$modal.confirm('是否确认删除亚马逊店铺信息编号为"' + _ids + '"的数据项？').finally(() => (loading.value = false));
  await delAmazonStore(_ids);
  proxy?.$modal.msgSuccess('删除成功');
  await getList();
};

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download(
    'amz/amazonStore/export',
    {
      ...queryParams.value
    },
    `amazonStore_${new Date().getTime()}.xlsx`
  );
};

onMounted(() => {
  getList();
});
</script>
