<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="编码" prop="goodsNo">
        <el-input
            v-model="queryParams.goodsNo"
            placeholder="请输入编码"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="名称" prop="goodsName">
        <el-input
            v-model="queryParams.goodsName"
            placeholder="请输入名称"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="品牌" prop="goodsBrand">
        <el-input
            v-model="queryParams.goodsBrand"
            placeholder="请输入品牌"
            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-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
            type="primary"
            plain
            icon="Plus"
            @click="handleAdd"
            v-hasPermi="['shop:goodsInfo:add']"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="success"
            plain
            icon="Edit"
            :disabled="single"
            @click="handleUpdate"
            v-hasPermi="['shop:goodsInfo:edit']"
        >修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="danger"
            plain
            icon="Delete"
            :disabled="multiple"
            @click="handleDelete"
            v-hasPermi="['shop:goodsInfo:remove']"
        >删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="warning"
            plain
            icon="Download"
            @click="handleExport"
            v-hasPermi="['shop:goodsInfo:export']"
        >导出
        </el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="goodsInfoList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="商品ID" align="center" prop="goodsId"/>
      <el-table-column label="编码" align="center" prop="goodsNo"/>
      <el-table-column label="名称" align="center" prop="goodsName"/>
      <el-table-column label="产地" align="center" prop="goodsPlace"/>
      <el-table-column label="品牌" align="center" prop="goodsBrand"/>
      <el-table-column label="规格" align="center" prop="goodsSpec"/>
      <el-table-column label="单位" align="center" prop="goodsUnit"/>
      <el-table-column label="库存" align="center" prop="goodsStock"/>
      <el-table-column label="价格" align="center" prop="goodsPrice"/>
      <el-table-column label="售价" align="center" prop="salePrice"/>
      <el-table-column label="二维码" align="center" prop="goodsQrcode"/>
      <el-table-column label="备注" align="center" prop="remark"/>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button
              type="text"
              icon="Edit"
              @click="handleUpdate(scope.row)"
              v-hasPermi="['shop:goodsInfo:edit']"
          >修改
          </el-button>
          <el-button
              type="text"
              icon="Delete"
              @click="handleDelete(scope.row)"
              v-hasPermi="['shop:goodsInfo:remove']"
          >删除
          </el-button>
        </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-dialog :title="title" v-model="open" width="700px" append-to-body draggable>
      <el-form ref="goodsInfoRef" :model="form" :rules="rules" label-width="80px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="编码" prop="goodsNo">
              <el-input v-model="form.goodsNo" placeholder="请输入编码"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="名称" prop="goodsName">
              <el-input v-model="form.goodsName" placeholder="请输入名称"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="产地" prop="goodsPlace">
          <!--          <el-input v-model="form.goodsPlace" placeholder="请输入产地" />-->
          <el-cascader
              size="large"
              :options="options"
              v-model="form.goodsPlace"
              @change="handleGoodsPlace">
          </el-cascader>
        </el-form-item>
        <el-row>
          <el-col :span="12">
            <el-form-item label="品牌" prop="goodsBrand">
              <el-input v-model="form.goodsBrand" placeholder="请输入品牌"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="规格" prop="goodsSpec">
              <el-input v-model="form.goodsSpec" placeholder="请输入规格"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="单位" prop="goodsUnit">
              <!--                <el-input v-model="form.goodsUnit" placeholder="请输入单位" />-->
              <el-select
                  v-model="form.goodsUnit"
                  filterable
                  allow-create
                  default-first-option
                  :reserve-keyword="false"
                  placeholder="请选择商品单位"
                  @change="handleGoodsUnit"

              >
                <el-option
                    v-for="item in GoodsOptions"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="库存" prop="goodsStock">
              <el-input v-model="form.goodsStock" placeholder="请输入库存"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="价格" prop="goodsPrice">
              <el-input v-model="form.goodsPrice" placeholder="请输入价格"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="售价" prop="salePrice">
              <el-input v-model="form.salePrice" placeholder="请输入售价"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="二维码" prop="goodsQrcode">
              <el-input v-model="form.goodsQrcode" placeholder="请输入二维码"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">

          </el-col>
        </el-row>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容"/>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="GoodsInfo">
import {listGoodsInfo, getGoodsInfo, delGoodsInfo, addGoodsInfo, updateGoodsInfo} from "@/api/shop/goodsInfo";
import {regionDataPlus, CodeToText} from 'element-china-area-data'

const {proxy} = getCurrentInstance();

const goodsInfoList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");

//校验输入编码规则
const checkGoodsNo = (rule, value, callback) => {
  if (value !== '' && value !== null) {
    if (!/^-?[1-9]\d*$/.test(value)) {
      callback(new Error('编码必须为数字'))
    } else if (!/^\d{6,9}$/.test(value)) {
      callback(new Error('编码必须为6-9位数字'))
    } else {
      callback()
    }
  } else {
    callback(new Error('编码不能为空'))
  }
}
//库存总量规则校验
const checkGoodsStock = (rules, value, callback) => {
  if (value !== '' && value !== null) {
    console.log(form.goodsUnit)
    if (form.goodsUnit !== 'kg') {
      if (!/^-?[1-9]\d*$/.test(value)) {
        callback(new Error('库存总量必须为整数'))
      } else if (value < 0) {
        callback(new Error('库存总量必须为正整数'))
      } else {
        callback()
      }
    } else {
      if (value < 0) {
        callback(new Error('库存总量不能小于0'))
      } else if (!/^((([^0][0-9]+|0)\.([0-9]{1,2}))$)|^(([1-9]+)\.([0-9]{1,3})$)/.test(value)) {
        callback(new Error('库存总量最多保留三位小数'))
      } else {
        callback()
      }
    }
  } else {
    callback(new Error('库存总量不能为空'))
  }
}
//商品价格规则校验
const checkGoodsPrice = (rules, value, callback) => {
  console.log()
  if (value !== '' && value !== null) {
    if (value < 0) {
      callback(new Error('商品价格不能为负数'))
    } else {
      //首位为小数点
      if (value.substr(0, 1) === '.') {
        callback(new Error('商品价格输入格式不正确'))
      } else if (!/^(([^0][0-9]+|0)\.([0-9])$)|^(([^0][0-9]+|0)$)|^(([1-9]+)\.([0-9]{1,3})$)|^(([1-9]+)$)/.test(value)) {
        callback(new Error('商品价格最多保留三位小数'))
      } else {
        callback()
      }
    }
  } else {
    callback(new Error('商品价格不能为空'))
  }
}

const options = regionDataPlus
const GoodsOptions = [
  {
    value: 'kg',
    label: '千克'
  },
  {
    value: '袋',
    label: '袋'
  },
  {
    value: '套',
    label: '套'
  },
  {
    value: '个',
    label: '个'
  },
  {
    value: '打',
    label: '打'
  },
  {
    value: '箱',
    label: '箱'
  },
  {
    value: '件',
    label: '件'
  }
]

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    goodsNo: null,
    goodsName: null,
    goodsBrand: null,
    goodsPlace: null
  },
  rules: {
    // goodsNo: [
    //   { required: true, message: "编码不能为空", trigger: "blur" },
    //   {type: 'number', message: "编码必须为数字", trigger: "blur"}
    // ],
    goodsNo: [
      {validator: checkGoodsNo, trigger: "blur"}
    ],
    goodsName: [
      {required: true, message: "名称不能为空", trigger: "blur"}
    ],
    goodsPlace: [
      {required: true, message: "产地不能为空", trigger: "blur"}
    ],
    goodsBrand: [
      {required: true, message: "品牌不能为空", trigger: "blur"}
    ],
    goodsSpec: [
      {required: true, message: "规格不能为空", trigger: "blur"}
    ],
    goodsUnit: [
      {required: true, message: "单位不能为空", trigger: "blur"}
    ],
    goodsStock: [
      {validator: checkGoodsStock, trigger: "blur"}
      // { required: true, message: "库存不能为空", trigger: "blur" }
    ],
    goodsPrice: [
      {validator: checkGoodsPrice, trigger: "blur"}
      // { required: true, message: "价格不能为空", trigger: "blur" }
    ],
    salePrice: [
      {validator: checkGoodsPrice, trigger: "blur"}
      // { required: true, message: "售价不能为空", trigger: "blur" }
    ],
    goodsQrcode: [
      {required: true, message: "二维码不能为空", trigger: "blur"}
    ],
  }
});

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

// 产地选择
function getCodeToText(codeStr, codeArray) {
  if (null === codeStr && null === codeArray) {
    return null;
  } else if (null === codeArray) {
    codeArray = codeStr.split(",");
  }
  let area = "";
  switch (codeArray.length) {
    case 1:
      area += CodeToText[codeArray[0]];
      break;
    case 2:
      area += CodeToText[codeArray[0]] + "/" + CodeToText[codeArray[1]];
      break;
    case 3:
      area +=
          CodeToText[codeArray[0]] +
          "/" +
          CodeToText[codeArray[1]] +
          "/" +
          CodeToText[codeArray[2]];
      break;
    default:
      break;
  }
  return area;
}

function handleGoodsPlace(value) {
  console.log(value)
  form.goodsPlace = getCodeToText(null, value)
}

// 商品单位选择
function handleGoodsUnit(value) {
  form.goodsUnit = value
}

/** 查询商品信息列表 */
function getList() {
  loading.value = true;
  listGoodsInfo(queryParams.value).then(response => {
    goodsInfoList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    goodsId: null,
    deptId: null,
    goodsNo: null,
    goodsName: null,
    goodsPlace: null,
    goodsBrand: null,
    goodsSpec: null,
    goodsUnit: null,
    goodsStock: null,
    goodsPrice: null,
    salePrice: null,
    goodsQrcode: null,
    goodsFields: null,
    createBy: null,
    createTime: null,
    updateBy: null,
    updateTime: null,
    remark: null
  };
  proxy.resetForm("goodsInfoRef");
}

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

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.goodsId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加商品信息";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _goodsId = row.goodsId || ids.value
  getGoodsInfo(_goodsId).then(response => {
    form.value = response.data;
    open.value = true;
    title.value = "修改商品信息";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["goodsInfoRef"].validate(valid => {
    if (valid) {
      if (form.value.goodsId != null) {
        updateGoodsInfo(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addGoodsInfo(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _goodsIds = row.goodsId || ids.value;
  proxy.$modal.confirm('是否确认删除商品信息编号为"' + _goodsIds + '"的数据项？').then(function () {
    return delGoodsInfo(_goodsIds);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {
  });
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('shop/goodsInfo/export', {
    ...queryParams.value
  }, `goodsInfo_${new Date().getTime()}.xlsx`)
}

getList();
</script>
