<template>
  <div class="dark:!bg-[#060818] p-4 bg-white">
    <div class="inner-toolbar w-11/12 mb-4">
      <div class="toolbar-search">
        <en-table-search
          class="!justify-start"
          @search="searchEvent"
          @advancedSearch="advancedSearchEvent"
          :placeholder="$t('search_placeholde')"
          advanced
          advancedWidth="465"
        >
          <template #advanced-content>
            <el-form ref="searchFormRef" v-model="searchForm" label-width="90px">
              <el-form-item label="仓库">
                <el-cascader
                  v-model="searchForm.dept_id"
                  :options="warehouseList"
                  :props="{
                    label: 'name',
                    value: 'id',
                    emitPath: false,
                    checkStrictly: true,
                  }"
                  clearable
                ></el-cascader>
              </el-form-item>
              <el-form-item label="状态">
                <el-select @click.stop v-model="searchForm.status" clearable :teleported="false">
                  <el-option key="NEW" label="新创建" value="NEW" />
                  <el-option key="CONFIRMED" label="已确认" value="CONFIRMED" />
                  <el-option key="RETURNED" label="已归还" value="RETURNED" />
                </el-select>
              </el-form-item>
            </el-form>
          </template>
        </en-table-search>
      </div>
      <div class="toolbar-btns mt-5">
        <el-button size="small" v-if="checkPermission(['warehouse:add']) && store.state.user.user.founder !== 1" type="primary" @click="handleAddWarehouse">{{
          $t('add')
        }}</el-button>
      </div>
    </div>
    <el-tabs v-model="activeName" class="demo-tabs" @tab-click="handleClick">
      <el-tab-pane :label="$t('whole')" name="first">
        <en-table-layout :tableData="tableData.records" :toolbar="false" :loading="loading">
          <template #table-columns>
            <el-table-column prop="name" :label="$t('order_sn')" />
            <el-table-column prop="brand" :label="$t('custom')" />
            <el-table-column prop="bar_code" :label="$t('order_time')" />
            <el-table-column prop="sku" :label="$t('warechouse_name')" />
            <el-table-column prop="weight" :label="$t('delivery_method')" />
            <el-table-column prop="unit" :label="$t('order_type')" />
            <el-table-column prop="image" :label="$t('user_state')">
              <template #default="scope">
                <img :src="scope.row.image" alt="" />
              </template>
            </el-table-column>
            <el-table-column :label="$t('operate')" fixed="right" width="450">
              <template #default="scope">
                <el-button size="small" v-if="checkPermission(['warehouse:update'])" @click="handleView(scope.row)">{{ $t('view') }}</el-button>
                <el-button
                  size="small"
                  v-if="checkPermission(['warehouse:update']) && store.state.user.user.founder !== 1"
                  @click="handleEditWarehouse(scope.$index, scope.row)"
                  >{{ $t('edit') }}</el-button
                >
                <el-button
                  type="success"
                  size="small"
                  v-if="checkPermission(['removeAreaType:delete']) && store.state.user.user.founder !== 1"
                  @click="handleDelGoods(scope.row)"
                  >{{ $t('delete') }}</el-button
                >
              </template>
            </el-table-column>
          </template>
          <template #pagination>
            <el-pagination
              v-if="tableData.records && tableData.records.length"
              @size-change="handlePageSizeChange"
              @current-change="handlePageCurrentChange"
              :current-page="tableData.page_no"
              :page-sizes="[10, 20, 50, 100]"
              :page-size="tableData.page_size"
              layout="total, sizes, prev, pager, next, jumper"
              :total="tableData.data_total"
            >
            </el-pagination>
          </template>
        </en-table-layout>
      </el-tab-pane>
      <el-tab-pane :label="$t('pending')" name="second">
        <en-table-layout :tableData="tableData.records" :toolbar="false" :loading="loading">
          <template #table-columns>
            <el-table-column prop="name" :label="$t('order_sn')" />
            <el-table-column prop="brand" :label="$t('custom')" />
            <el-table-column prop="bar_code" :label="$t('order_time')" />
            <el-table-column prop="sku" :label="$t('warechouse_name')" />
            <el-table-column prop="weight" :label="$t('delivery_method')" />
            <el-table-column prop="unit" :label="$t('order_type')" />
            <el-table-column prop="image" :label="$t('user_state')">
              <template #default="scope">
                <img :src="scope.row.image" alt="" />
              </template>
            </el-table-column>
            <el-table-column :label="$t('operate')" fixed="right" width="450">
              <template #default="scope">
                <el-button size="small" v-if="checkPermission(['warehouse:update'])" @click="handleView(scope.row)">{{ $t('view') }}</el-button>
                <el-button
                  size="small"
                  v-if="checkPermission(['warehouse:update']) && store.state.user.user.founder !== 1"
                  @click="handleEditWarehouse(scope.$index, scope.row)"
                  >{{ $t('edit') }}</el-button
                >
                <el-button
                  type="success"
                  size="small"
                  v-if="checkPermission(['removeAreaType:delete']) && store.state.user.user.founder !== 1"
                  @click="handleDelGoods(scope.row)"
                  >{{ $t('delete') }}</el-button
                >
              </template>
            </el-table-column>
          </template>
          <template #pagination>
            <el-pagination
              v-if="tableData.records && tableData.records.length"
              @size-change="handlePageSizeChange"
              @current-change="handlePageCurrentChange"
              :current-page="tableData.page_no"
              :page-sizes="[10, 20, 50, 100]"
              :page-size="tableData.page_size"
              layout="total, sizes, prev, pager, next, jumper"
              :total="tableData.data_total"
            >
            </el-pagination>
          </template>
        </en-table-layout>
      </el-tab-pane>
      <el-tab-pane :label="$t('unshipped')" name="third">
        <en-table-layout :tableData="tableData.records" :toolbar="false" :loading="loading">
          <template #table-columns>
            <el-table-column prop="name" :label="$t('order_sn')" />
            <el-table-column prop="brand" :label="$t('custom')" />
            <el-table-column prop="bar_code" :label="$t('order_time')" />
            <el-table-column prop="sku" :label="$t('warechouse_name')" />
            <el-table-column prop="weight" :label="$t('delivery_method')" />
            <el-table-column prop="unit" :label="$t('order_type')" />
            <el-table-column prop="image" :label="$t('user_state')">
              <template #default="scope">
                <img :src="scope.row.image" alt="" />
              </template>
            </el-table-column>
            <el-table-column :label="$t('operate')" fixed="right" width="450">
              <template #default="scope">
                <el-button size="small" v-if="checkPermission(['warehouse:update'])" @click="handleView(scope.row)">{{ $t('view') }}</el-button>
                <el-button
                  size="small"
                  v-if="checkPermission(['warehouse:update']) && store.state.user.user.founder !== 1"
                  @click="handleEditWarehouse(scope.$index, scope.row)"
                  >{{ $t('edit') }}</el-button
                >
                <el-button
                  type="success"
                  size="small"
                  v-if="checkPermission(['removeAreaType:delete']) && store.state.user.user.founder !== 1"
                  @click="handleDelGoods(scope.row)"
                  >{{ $t('delete') }}</el-button
                >
              </template>
            </el-table-column>
          </template>
          <template #pagination>
            <el-pagination
              v-if="tableData.records && tableData.records.length"
              @size-change="handlePageSizeChange"
              @current-change="handlePageCurrentChange"
              :current-page="tableData.page_no"
              :page-sizes="[10, 20, 50, 100]"
              :page-size="tableData.page_size"
              layout="total, sizes, prev, pager, next, jumper"
              :total="tableData.data_total"
            >
            </el-pagination>
          </template>
        </en-table-layout>
      </el-tab-pane>
      <el-tab-pane :label="$t('shipped')" name="fourth">
        <en-table-layout :tableData="tableData.records" :toolbar="false" :loading="loading">
          <template #table-columns>
            <el-table-column prop="name" :label="$t('order_sn')" />
            <el-table-column prop="brand" :label="$t('custom')" />
            <el-table-column prop="bar_code" :label="$t('order_time')" />
            <el-table-column prop="sku" :label="$t('warechouse_name')" />
            <el-table-column prop="weight" :label="$t('delivery_method')" />
            <el-table-column prop="unit" :label="$t('order_type')" />
            <el-table-column prop="image" :label="$t('user_state')">
              <template #default="scope">
                <img :src="scope.row.image" alt="" />
              </template>
            </el-table-column>
            <el-table-column :label="$t('operate')" fixed="right" width="450">
              <template #default="scope">
                <el-button size="small" v-if="checkPermission(['warehouse:update'])" @click="handleView(scope.row)">{{ $t('view') }}</el-button>
                <el-button
                  size="small"
                  v-if="checkPermission(['warehouse:update']) && store.state.user.user.founder !== 1"
                  @click="handleEditWarehouse(scope.$index, scope.row)"
                  >{{ $t('edit') }}</el-button
                >
                <el-button
                  type="success"
                  size="small"
                  v-if="checkPermission(['removeAreaType:delete']) && store.state.user.user.founder !== 1"
                  @click="handleDelGoods(scope.row)"
                  >{{ $t('delete') }}</el-button
                >
              </template>
            </el-table-column>
          </template>
          <template #pagination>
            <el-pagination
              v-if="tableData.records && tableData.records.length"
              @size-change="handlePageSizeChange"
              @current-change="handlePageCurrentChange"
              :current-page="tableData.page_no"
              :page-sizes="[10, 20, 50, 100]"
              :page-size="tableData.page_size"
              layout="total, sizes, prev, pager, next, jumper"
              :total="tableData.data_total"
            >
            </el-pagination>
          </template>
        </en-table-layout>
      </el-tab-pane>
      <el-tab-pane :label="$t('refunded')" name="refunded">
        <en-table-layout :tableData="tableData.records" :toolbar="false" :loading="loading">
          <template #table-columns>
            <el-table-column prop="name" :label="$t('order_sn')" />
            <el-table-column prop="brand" :label="$t('custom')" />
            <el-table-column prop="bar_code" :label="$t('order_time')" />
            <el-table-column prop="sku" :label="$t('warechouse_name')" />
            <el-table-column prop="weight" :label="$t('delivery_method')" />
            <el-table-column prop="unit" :label="$t('order_type')" />
            <el-table-column prop="image" :label="$t('user_state')">
              <template #default="scope">
                <img :src="scope.row.image" alt="" />
              </template>
            </el-table-column>
            <el-table-column :label="$t('operate')" fixed="right" width="450">
              <template #default="scope">
                <el-button size="small" v-if="checkPermission(['warehouse:update'])" @click="handleView(scope.row)">{{ $t('view') }}</el-button>
                <el-button
                  size="small"
                  v-if="checkPermission(['warehouse:update']) && store.state.user.user.founder !== 1"
                  @click="handleEditWarehouse(scope.$index, scope.row)"
                  >{{ $t('edit') }}</el-button
                >
                <el-button
                  type="success"
                  size="small"
                  v-if="checkPermission(['removeAreaType:delete']) && store.state.user.user.founder !== 1"
                  @click="handleDelGoods(scope.row)"
                  >{{ $t('delete') }}</el-button
                >
              </template>
            </el-table-column>
          </template>
          <template #pagination>
            <el-pagination
              v-if="tableData.records && tableData.records.length"
              @size-change="handlePageSizeChange"
              @current-change="handlePageCurrentChange"
              :current-page="tableData.page_no"
              :page-sizes="[10, 20, 50, 100]"
              :page-size="tableData.page_size"
              layout="total, sizes, prev, pager, next, jumper"
              :total="tableData.data_total"
            >
            </el-pagination>
          </template>
        </en-table-layout>
      </el-tab-pane>
    </el-tabs>

    <el-dialog
      :title="skuForm.id ? $t('edit') : $t('add')"
      v-model="dialogVisible"
      @open="handleDialogOpen"
      :modal-append-to-body="false"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      class="!rounded-lg"
    >
      <el-form :model="skuForm" :rules="stockRules" ref="skuFormRef" label-width="140px">
        <el-row>
          <!--<el-col :span="10" v-if="!skuForm.id">
                <el-form-item label="套餐:" prop="company_package_id">
                  <el-select v-model="skuForm.company_package_id" clearable placeholder="请选择套餐">
                    <el-option v-for="item in packageList" :key="item.id" :label="item.name" :value="item.id" />
                  </el-select>
                </el-form-item>
              </el-col> -->
          <el-col :span="10">
            <el-form-item :label="$t('goods_name') + ':'" prop="name">
              <el-input
                v-model="skuForm.name"
                :minlength="2"
                :maxlength="20"
                :disabled="disabled"
                clearable
                :placeholder="$t('place') + $t('goods_name')"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="10">
            <el-form-item :label="$t('goods_brand') + ':'" prop="brand">
              <el-input
                v-model="skuForm.brand"
                :minlength="2"
                :maxlength="20"
                :disabled="disabled"
                clearable
                :placeholder="$t('place') + $t('goods_brand')"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="10">
            <el-form-item :label="$t('goods_bar_code') + ':'" prop="bar_code">
              <el-input
                v-model="skuForm.bar_code"
                :minlength="2"
                :maxlength="20"
                :disabled="disabled"
                clearable
                :placeholder="$t('place') + $t('goods_bar_code')"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="10">
            <el-form-item label="sku:" prop="sku">
              <el-input v-model="skuForm.sku" :minlength="2" :maxlength="20" :disabled="disabled" clearable :placeholder="$t('place') + 'sku'"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="10">
            <el-form-item :label="$t('goods_weight') + ':'" prop="weight">
              <el-input
                v-model="skuForm.weight"
                :minlength="2"
                :maxlength="20"
                :disabled="disabled"
                clearable
                :placeholder="$t('place') + $t('goods_weight')"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="10">
            <el-form-item :label="$t('goods_unit') + ':'" prop="unit">
              <el-input
                v-model="skuForm.unit"
                :minlength="2"
                :maxlength="20"
                :disabled="disabled"
                clearable
                :placeholder="$t('place') + $t('goods_unit')"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="10">
            <el-form-item :label="$t('goods_image') + ':'" prop="image">
              <el-upload
                class="avatar-uploader"
                :action="uploadUrl"
                :show-file-list="false"
                :disabled="disabled"
                :on-success="handleAvatarSuccess"
                :before-upload="beforeAvatarUpload"
              >
                <img v-if="skuForm.image" :src="skuForm.image" class="avatar w-28 h-28" />
                <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
              </el-upload>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">{{ $t('cancel') }}</el-button>
          <el-button type="primary" @click="submitWarehouseForm">{{ $t('submit') }}</el-button>
        </div>
      </template>
    </el-dialog>
    <!-- <el-dialog title="续费" v-model="renewVisible" :modal-append-to-body="false" width="450px" :close-on-click-modal="false" :close-on-press-escape="false">
          <el-form :model="packageForm" :rules="stockRules" ref="packageFormRef" label-width="140px">
            <el-form-item label="套餐:" prop="company_package_id">
              <el-select v-model="packageForm.company_package_id" clearable placeholder="请选择套餐">
                <el-option v-for="item in packageList" :key="item.id" :label="item.name" :value="item.id" />
              </el-select>
            </el-form-item>
          </el-form>
          <template #footer>
            <div class="dialog-footer">
              <el-button @click="renewVisible = false">取 消</el-button>
              <el-button type="primary" @click="submitPackageForm">确 定</el-button>
            </div>
          </template>
        </el-dialog> -->
  </div>
</template>
        
        <script lang="ts" setup>
import { ref, onMounted } from 'vue';
import { useStore } from 'vuex';
import { ElMessageBox, FormInstance, ElMessage, TabsPaneContext } from 'element-plus';
import * as API_BasicSetting from '@/api/basicSetting';
import * as API_Setting from '@/api/setting';
import * as API_Company from '@/api/company';
import * as API_Goods from '@/api/goods';
import Storage from '@/utils/storage';
import router from '@/router';
import { provinceAndCityData, pcTextArr, regionData, pcaTextArr, codeToText } from 'element-china-area-data';
import { Plus } from '@element-plus/icons-vue';
import type { UploadProps } from 'element-plus';
import { useI18n } from 'vue-i18n';

const { t } = useI18n();

const handleAvatarSuccess: UploadProps['onSuccess'] = (response, uploadFile) => {
  console.log(response, uploadFile);
  skuForm.value.image = response.url; //URL.createObjectURL(uploadFile.raw!);
};

const uploadUrl = ref(import.meta.env.VITE_API_URL + '/uploaders');
const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
  if (rawFile.size / 1024 / 1024 > 10) {
    ElMessage.error('Avatar picture size can not exceed 10MB!');
    return false;
  }
  return true;
};
/* 仓库列表 */
const warehouseList = ref([]);
/* 搜索表单 */
const searchForm = ref({
  dept_id: '',
  status: '',
});

/* 切换分页 */
const activeName = ref('first');

const handleClick = (tab: TabsPaneContext, event: Event) => {
  if (tab.props.name == 'first') {
    GET_GoodsList();
  } else if (tab.props.name == 'second') {
    GET_GoodsList();
  } else if (tab.props.name == 'third') {
    GET_GoodsList();
  } else if (tab.props.name == 'fourth') {
    GET_GoodsList();
  } else if (tab.props.name == 'refunded') {
    GET_GoodsList();
  }
};
const store = useStore();
const tableData = ref<any>({});
const loading = ref(false);
const dialogVisible = ref(false);
const skuForm = ref<any>({
  name: '',
  brand: '',
  snCode: '',
  bar_code: '',
  sku: '',
  weight: '',
  image: '',
  unit: '',
});
const stockRules = ref<any>({
  name: [{ required: true, message: t('place') + t('goods_name') + '!', trigger: 'blur' }],
  brand: [{ required: true, message: t('place') + t('goods_brand') + '!', trigger: 'blur' }],
  snCode: [{ required: true, message: '请输入商品序列号!', trigger: 'blur' }],
  bar_code: [{ required: true, message: t('place') + t('goods_bar_code') + '!', trigger: 'blur' }],
  sku: [{ required: true, message: t('place') + 'sku!', trigger: 'blur' }],
  weight: [{ required: true, message: t('place') + t('goods_weight') + '!', trigger: 'blur' }],
  postal_code: [{ required: true, message: t('place') + t('goods_unit') + '!', trigger: 'blur' }],
  image: [{ required: true, message: t('place') + t('goods_image') + '!', trigger: 'blur' }],
});
const selectedOptions = ref<any[]>([]);
const marketingList = ref<any[]>([]);
const options = ref<any[]>(regionData);
const params = ref({
  data: [],
  page_no: 1,
  page_size: 10,
  keyword: '',
  company_id: store.state.companId,
});
const roleArray = ref<any[]>([]);
const disabled = ref(false);

const renewVisible = ref(false);
/* 套餐 */
const packageForm = ref<any>({
  company_package_id: '',
  this_money: '',
});
let packageId = ref('');
let companyId = ref('');
const packageFormRef = ref();

const handleBranch = (index: number, row: any) => {
  router.push({ name: 'branch' });
};

/* 续费 */
const handleRenew = (index: number, row: any) => {
  packageForm.value.company_package_id = row.company_package_id;
  companyId.value = row.id;
  packageId.value = row.company_package_id;
  API_Company.companyPackage(row.company_package_id).then((res) => {
    packageForm.value.this_money = res.money;
    renewVisible.value = true;
  });
};
const skuFormRef = ref();
const checkPermission = (permissions: string[]): boolean => {
  // Implement your permission check logic here
  return true;
};

const handleAddWarehouse = () => {
  selectedOptions.value = [];
  skuForm.value = {};
  disabled.value = false;
  dialogVisible.value = true;
};

const handleEditWarehouse = (index: number, row: any) => {
  skuForm.value = { ...row };
  disabled.value = false;
  selectedOptions.value = row.province;
  dialogVisible.value = true;
};

const searchEvent = (keyword: string) => {
  params.value = {
    ...params.value,
    keyword: keyword,
  };
  params.value.page_no = 1;
  GET_GoodsList();
};

const handlePageSizeChange = (size: number) => {
  params.value.page_size = size;
  GET_GoodsList();
};

const handlePageCurrentChange = (page: number) => {
  params.value.page_no = page;
  GET_GoodsList();
};

const handleDialogOpen = () => {
  setTimeout(() => {
    skuFormRef.value.clearValidate();
  });
};

const submitWarehouseForm = () => {
  skuFormRef.value.validate((valid: boolean) => {
    if (valid) {
      const { id } = skuForm.value;
      const params = { ...skuForm.value };
      if (id) {
        API_Goods.editProduct(id, params).then(() => {
          dialogVisible.value = false;
          ElMessage.success(t('edit_success') + '!');
          GET_GoodsList();
        });
      } else {
        API_Goods.addProduct(params).then(() => {
          dialogVisible.value = false;
          ElMessage.success(t('add_success') + '!');
          GET_GoodsList();
        });
      }
    } else {
      ElMessage.error(t('form_erroe') + '!');
      /*    store.dispatch('showMessage', { message: '表单填写有误，请核对！', type: 'error' }); */
      return false;
    }
  });
};

const GET_GoodsList = () => {
  /*  loading.value = true;
   API_Goods.productList(params.value)
    .then((response) => {
      loading.value = false;
      tableData.value = response;
    })
    .catch(() => {
      loading.value = false;
    }); */
};

/* 删除 */
const handleDelGoods = (row) => {
  ElMessageBox.confirm(t('del_info'), t('prompt'), { type: 'warning' })
    .then(() => {
      API_Goods.delProduct(row.id).then(() => {
        ElMessage.success(t('del_success') + '!');
        GET_GoodsList();
      });
    })
    .catch(() => {});
};
const adminName = (val: string[]) => {
  let text = '';
  if (val !== undefined) {
    text += codeToText[val[0]];
    text += codeToText[val[1]];
    text += codeToText[val[2]];
  }
  return text;
};

/* 切换菜单 */

const handleView = (row) => {
  skuForm.value = { ...row };
  disabled.value = true;
  dialogVisible.value = true;
};
/* 高级搜索 */
const advancedSearchEvent = () => {
  GET_GoodsList();
};
onMounted(() => {
  GET_GoodsList();
  /*  GET_MarketingList();
    GET_PackageList(); */
});
</script>
    <style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 112px;
  height: 112px;
  text-align: center;
}
</style>
    