<template>
  <div>
    <en-table-layout :tableData="tableData.records" :loading="loading">
      <template #toolbar>
        <div class="inner-toolbar w-11/12 flex justify-between">
          <div class="toolbar-btns">
            <el-button size="small" v-if="checkPermission(['warehouse:add'])&& store.state.user.user.founder!==1" type="primary" @click="handleAddWarehouse">新增</el-button>
          </div>
          <div class="toolbar-search">
            <en-table-search @search="searchEvent" placeholder="请输入关键字搜索" />
          </div>
        </div>
      </template>

      <template #table-columns>
        <el-table-column prop="name" label="产品名称" />
        <el-table-column prop="brand" label="品牌" />
        <el-table-column prop="bar_code" label="条码" />
        <el-table-column prop="sku" label="sku" />
        <el-table-column prop="weight" label="重量" />
        <el-table-column prop="unit" label="单位" />
        <el-table-column prop="image" label="产品图片">
          <template #default="scope">
            <img :src="scope.row.image" alt="" />
          </template>
        </el-table-column>

        <el-table-column label="操作">
          <template #default="scope">
            <el-button size="small" v-if="checkPermission(['warehouse:update'])" @click="handleView(scope.row)">查看</el-button>
            <el-button size="small" v-if="checkPermission(['warehouse:update'])&& store.state.user.user.founder!==1" @click="handleEditWarehouse(scope.$index, scope.row)">编辑</el-button>
            <el-button type="success" size="small" v-if="checkPermission(['removeAreaType:delete'])&& store.state.user.user.founder!==1" @click="handleDelGoods(scope.row)">删除</el-button>
            <!--<el-button size="mini" v-if="checkPermission(['warehouse:update'])" @click="handleRenew(scope.$index, scope.row)">续费</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-dialog
      :title="skuForm.id ? '编辑商品' : '新建商品'"
      v-model="dialogVisible"
      @open="handleDialogOpen"
      :modal-append-to-body="false"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
    >
      <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="产品名称:" prop="name">
              <el-input v-model="skuForm.name" :minlength="2" :maxlength="20" :disabled="disabled" clearable placeholder="请输入产品名称"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="10">
            <el-form-item label="品牌:" prop="brand">
              <el-input v-model="skuForm.brand" :minlength="2" :maxlength="20" :disabled="disabled" clearable placeholder="请输入品牌"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="10">
            <el-form-item label="条码:" prop="bar_code">
              <el-input v-model="skuForm.bar_code" :minlength="2" :maxlength="20" :disabled="disabled" clearable placeholder="请输入条码"></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="请输入sku"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="10">
            <el-form-item label="重量:" prop="weight">
              <el-input v-model="skuForm.weight" :minlength="2" :maxlength="20" :disabled="disabled" clearable placeholder="请输入重量"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="10">
            <el-form-item label="单位:" prop="unit">
              <el-input v-model="skuForm.unit" :minlength="2" :maxlength="20" :disabled="disabled" clearable placeholder="请输入单位"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="10">
            <el-form-item label="产品图片:" 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">取 消</el-button>
          <el-button type="primary" @click="submitWarehouseForm">确 定</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 } 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';

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 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: '请输入产品名称!', trigger: 'blur' }],
  brand: [{ required: true, message: '请输入品牌!', trigger: 'blur' }],
  snCode: [{ required: true, message: '请输入商品序列号!', trigger: 'blur' }],
  bar_code: [{ required: true, message: '请输入条码!', trigger: 'blur' }],
  sku: [{ required: true, message: '请输入sku!', trigger: 'blur' }],
  weight: [{ required: true, message: '请输入重量!', trigger: 'blur' }],
  postal_code: [{ required: true, message: '请输入单位!', trigger: 'blur' }],
  image: [{ required: true, message: '请输入上传产品图片!', 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('修改成功！');
          GET_GoodsList();
        });
      } else {
        API_Goods.addProduct(params).then(() => {
          dialogVisible.value = false;
          ElMessage.success('添加成功！');
          GET_GoodsList();
        });
      }
    } else {
      ElMessage.error('表单填写有误，请核对！');
      /*    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('确定要删除吗？', '提示', { type: 'warning' })
    .then(() => {
      API_Goods.delProduct(row.id).then(() => {
        ElMessage.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;
};

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>
  