<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" @submit.native.prevent :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="商品名称" prop="title">
        <el-input v-model="queryParams.title" placeholder="请输入商品名称" clearable @keyup.enter.native="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="['system:product:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete" v-hasPermi="['system:product:remove']">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="Download" @click="handleExport" v-hasPermi="['system:product:export']">导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="productList" :row-key="getRowKeys" stripe :expand-row-keys="expands" @expand-change="expandLoad" @selection-change="handleSelectionChange">
      <el-table-column label="id" align="center" prop="id" />
      <el-table-column label="商品名称" align="center" prop="title" />
      <el-table-column label="商品图片" align="center" prop="images">
        <template #default="scope">
          <el-image
            class="mr5"
            lazy
            v-for="(item, index) in scope.row.images"
            preview-teleported
            :initial-index="index"
            :preview-src-list="scope.row.images"
            :src="item"
            :key="item"
            style="width: 20px; height: 20px"
          />
        </template>
      </el-table-column>
      <el-table-column label="是否显示" align="center" prop="isShow">
        <template #default="scope">
          <el-button type="primary" @click="productChangeShow(scope.row)" v-hasPermi="['system:product:edit']">{{ scope.row.isShow ? '显示' : '隐藏' }}</el-button>
        </template>
      </el-table-column>
      <el-table-column label="商品备注" show-overflow-tooltip align="center" prop="remark" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['system:product:edit']">修改</el-button>
          <el-button link type="primary" icon="FolderRemove" @click="handlePrice(scope.row)" v-hasPermi="['system:product:edit']">修改价格</el-button>
          <el-button link type="primary" icon="CirclePlus" @click="handleMate(scope.row)" v-hasPermi="['system:product:add']">添加材质</el-button>
          <el-button link type="primary" icon="Folder" @click="handleImage(scope.row)" v-hasPermi="['system:product:edit']">修改图片</el-button>
          <el-button link type="primary" icon="Edit" @click="handleRemark(scope.row)" v-hasPermi="['system:product:RemarkEdit']">修改备注</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['system:product:remove']">删除</el-button>
        </template>
      </el-table-column>
      <el-table-column type="expand" class="el-flex">
        <template #default="props">
          <div class="el-flex" style="justify-content: center">
            <div style="width: 90%; justify-content: center">
              <el-table class="table-bordered" :data="props.row.children">
                <el-table-column label="材质名称" align="center" prop="title" />
                <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
                  <template #default="scope">
                    <el-button link type="primary" icon="CirclePlus" @click="handleEditMate(scope.row)" v-hasPermi="['system:product:add']">修改材质</el-button>
                    <el-button link type="primary" icon="Delete" @click="handleMateDelete(scope.row)" v-hasPermi="['system:product:remove']">删除</el-button>
                  </template>
                </el-table-column>
              </el-table>
            </div>
          </div>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize" @pagination="getList" />

    <!-- 添加或修改商品对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="productForm" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="商品名称" prop="title">
          <el-input v-model="form.title" placeholder="请输入商品名称" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 添加或修改商品价格对话框 -->
    <el-dialog :title="priceTitle" v-model="price_open" @submit.native.prevent append-to-body width="60%">
      <el-form ref="priceForm" :model="priceform">
        <div style="color: #f56; font-weight: bold">
          <template v-if="priceform.modes == 0">
            <span>位数计算基础为基本面积</span>
          </template>
          <template v-if="priceform.modes == 1">
            <span>面积计算基础为面积的计算方式，可用参数为width(宽)，height(高)，count(数量)，number(款数)</span>
          </template>
        </div>

        <div class="el-flex">
          <el-form-item label="单位计算方式" prop="modes" class="mr10">
            <el-select v-model="priceform.modes" placeholder="单位计算方式">
              <el-option v-for="item in jisuan" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>
          <el-form-item label="基础" prop="basics" v-if="priceform.modes != 2" class="mr10">
            <el-input v-model="priceform.basics" placeholder="基础" />
          </el-form-item>
          <el-form-item label="是否开启多面" prop="isMore" class="mr10">
            <el-checkbox label="开启" v-model="priceform.isMore"></el-checkbox>
          </el-form-item>
          <el-form-item label="是否开启比价" prop="isParity" class="mr10">
            <el-checkbox label="开启" v-model="priceform.isParity"></el-checkbox>
          </el-form-item>
          <el-form-item label="倍率" prop="power" v-if="priceform.isParity">
            <el-input v-model="priceform.power" placeholder="倍率" />
          </el-form-item>
        </div>
        <div style="color: #f56; font-weight: bold">
          <span>款式计算为底价计算公式后的附加价格，可用参数为price(底价)，count(数量)，number(款数)</span>
        </div>
        <el-form-item label="款式计算" prop="styleCompute">
          <el-input v-model="priceform.styleCompute" placeholder="款式计算" />
        </el-form-item>
        <el-form-item label="价格计算方式" prop="calculateEnum" class="mr10">
          <el-select v-model="priceform.calculateEnum" placeholder="价格计算方式">
            <el-option v-for="item in calculateEnum" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <template v-if="priceform.calculateEnum == 1">
          <div style="color: #f56; font-weight: bold">
            <span>价格公式计算价格的公式，可用参数为width(宽)，height(高)，count(数量)，number(款数)</span>
          </div>
          <el-form-item label="价格公式" prop="computeStr" class="mr10">
            <el-input v-model="priceform.computeStr" placeholder="价格公式" />
          </el-form-item>
        </template>
        <template v-if="priceform.calculateEnum == 0">
          <ExcelImport @inportExcel="inportExcel" />
          <editTable :columnList="columnList" :datas="datas"></editTable>
        </template>
        <div style="color: #f56; font-weight: bold">
          <span>底价计算为上方价格计算后的附加价格，可用参数为price(底价)，count(数量)，number(款数)，x(位数计算就是位数，面积计算就是面积)</span>
        </div>
        <el-form-item class="mt10" label="底价计算" prop="formula">
          <el-input v-model="priceform.formula" placeholder="款式计算" />
        </el-form-item>
        <addCraft v-model:data="cates" />
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="priceSubmit">确 定</el-button>
          <el-button @click="priceCancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 添加或修改材质价格对话框 -->
    <el-dialog :title="mateTitle" v-model="mate_open" @submit.native.prevent append-to-body width="60%">
      <el-form ref="mateForm" :model="mateform">
        <div class="el-flex">
          <el-form-item label="材质名称" prop="title" class="mr10">
            <el-input v-model="mateform.title" placeholder="材质名称" />
          </el-form-item>
          <el-form-item label="是否开启自己的计算" prop="isUseSelf" class="mr10">
            <el-checkbox label="开启" v-model="mateform.isUseSelf"></el-checkbox>
          </el-form-item>
        </div>
        <el-form-item label="价格计算方式" prop="calculateEnum" class="mr10">
          <el-select v-model="mateform.calculateEnum" placeholder="价格计算方式">
            <el-option v-for="item in calculateEnum" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <template v-if="mateform.calculateEnum == 1">
          <el-form-item label="价格公式" prop="computeStr" class="mr10">
            <el-input v-model="mateform.computeStr" placeholder="价格公式" />
          </el-form-item>
        </template>
        <template v-if="mateform.calculateEnum == 0">
          <ExcelImport @inportExcel="inportExcel" />
          <editTable :columnList="columnList" :datas="datas" v-if="mateform.isUseSelf"></editTable>
        </template>
        <addCraft v-model:data="cates" />
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="mateSubmit">确 定</el-button>
          <el-button @click="mateCancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <!--修改商品备注-->
    <el-dialog :title="remarkTitle" v-model="remark_open" @submit.native.prevent append-to-body width="60%">
      <el-form ref="remarkForm" :model="remarkform">
        <el-form-item label="备注" prop="remark">
          <el-input v-model="remarkform.remark" placeholder="备注" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="remarkSubmit">确 定</el-button>
          <el-button @click="remarkCancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <!--修改图片-->
    <el-dialog :title="imageTitle" v-model="image_open" @submit.native.prevent append-to-body width="60%">
      <el-form ref="imageForm" :model="imageform">
        <ImageUpload :limit="5" v-model:modelValue="imageform.images" />
        <el-form-item label="图片说明" prop="imageText">
          <el-input v-model="imageform.imageText" placeholder="图片说明" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="imageSubmit">确 定</el-button>
          <el-button @click="imageCancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Product">
import { listProduct, getProduct, delProduct, addProduct, updateProduct, updatePrice, addMate, editMate, listMaterial, getMate, delMate, updateRemark } from '@/api/system/product';
import editTable from '@/components/editTable';
import addCraft from '@/components/AddCraft';
import ExcelImport from '@/components/ExcelImport';
import ImageUpload from '@/components/ImageUpload';

const { proxy } = getCurrentInstance();
const cates = ref([]);
const jisuan = [
  {
    label: '位数计算',
    value: 0,
  },
  {
    label: '面积计算',
    value: 1,
  },
  {
    label: '长宽计算',
    value: 2,
  },
];

const calculateEnum = [
  {
    label: '梯度',
    value: 0,
  },
  {
    label: '公式',
    value: 1,
  },
];
// 遮罩层
const loading = ref(true);
// 选中数组
const ids = ref([]);
// 非单个禁用
const single = ref(true);
// 非多个禁用
const multiple = ref(true);
// 显示搜索条件
const showSearch = ref(true);
// 总条数
const total = ref(0);
// 商品表格数据
const productList = ref([]);
// 弹出层标题
const title = ref('');
// 是否显示弹出层
const open = ref(false);
const expands = ref([]);
const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    title: null,
    orderByColumn: 'id',
    isAsc: 'desc',
  },
  rules: {
    title: [{ required: true, message: '商品名称不能为空', trigger: 'blur' }],
  },
});

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

/**导入excel数据 */
function inportExcel(data) {
  columnList.value = data.columnList.value;
  datas.value = data.datas.value;
}

/**下级展开 */
async function expandLoad(row, expandedRows) {
  expands.value = [];

  if (expandedRows.length > 0) {
    expands.value.push(row.id);
    let { code, msg, rows } = await listMaterial({ productId: row.id });
    if (code === 200) {
      row.children = rows;
    }
  }
}

function getRowKeys(row) {
  return row.id;
}

/**修改图片开始 */

const image_open = ref(false);
const imageTitle = ref('');
const imageform = ref({});

function handleImage(row) {
  imageTitle.value = '修改图片';
  imageform.value = { id: row.id, images: row.images, imageText: row.imageText };
  image_open.value = true;
}
function imageSubmit() {
  let msg = `是否确认修改图片？`;
  console.log('🚀 ~ file: index.vue:284 ~ updateProduct ~ imageform.value:', imageform.value);
  proxy.$modal
    .confirm(msg)
    .then(function () {
      imageform.value.images = imageform.value.images.split(',');
      updateProduct(imageform.value).then(response => {
        if (response.code === 200) {
          proxy.$message.success('修改成功');
          image_open.value = false;
          getList();
        }
      });
    })
    .catch(function () {
      //取消
      imageCancel();
    });
}
function imageCancel() {
  image_open.value = false;
}

/**修改图片结束 */

/**修改备注开始 */

const remark_open = ref(false);
const remarkTitle = ref('');
const remarkform = ref({});

function handleRemark(row) {
  remarkTitle.value = '修改备注';
  remarkform.value = { id: row.id, remark: row.remark };
  remark_open.value = true;
}

function remarkSubmit() {
  let msg = `是否确认修改备注？`;
  proxy.$modal
    .confirm(msg)
    .then(function () {
      updateRemark(remarkform.value).then(response => {
        if (response.code === 200) {
          proxy.$message.success('修改成功');
          remark_open.value = false;
          getList();
        }
      });
    })
    .catch(function () {
      //取消
      remarkCancel();
    });
}
function remarkCancel() {
  remark_open.value = false;
}

/**修改备注结束 */
/**材质开始 */
const mate_open = ref(false);
const mateTitle = ref('');
const mateform = ref({});

function handleMate(row) {
  mateTitle.value = '添加材质';
  mateform.value = {};
  mateform.value.productId = row.id;
  mate_open.value = true;
  cates.value = [];
}

function mateSubmit() {
  let list = {};
  datas.value.map(item => {
    let json = { ...item };
    let key = json.area;
    delete json.area;
    delete json.row_index;
    list[key] = json;
  });
  mateform.value.compute = JSON.stringify(list);

  cates.value.map(item => {
    item.children?.map(k => {
      /**判断是否数组 */
      if (Array.isArray(k.repel)) {
        k.repel = k?.repel?.join('|');
      }
    });
  });
  let msg = `是否确认添加材质${mateform.value.title}？`;
  if (mateform.value.id) {
    msg = `是否确认修改材质${mateform.value.title}？`;
  }
  proxy.$modal
    .confirm(msg)
    .then(function () {
      if (mateform.value.id) {
        return editMate({ ...mateform.value, productCates: [...cates.value] });
      }
      return addMate({ ...mateform.value, productCates: [...cates.value] });
    })
    .then(() => {
      getList();
      mate_open.value = false;
      if (mateform.value.id) {
        return proxy.$modal.msgSuccess('修改成功');
      }
      proxy.$modal.msgSuccess('添加成功');
    })
    .catch(() => {});
}

function mateCancel() {
  mate_open.value = false;
}

async function handleEditMate(row) {
  let { code, data, msg } = await getMate(row.id);
  if (code === 200) {
    mate_open.value = true;
    priceTitle.value = `修改【${row.title}】价格`;
    mateform.value = data;
    if (!mateform.value.calculateEnum) {
      mateform.value.calculateEnum = 0;
    }
    let compute = data.compute;
    compute = JSON.parse(compute);
    cates.value = data.productCates || [];
    columnList.value = [{ prop: 'area', label: '面积/数量' }];
    datas.value = [];
    cates.value?.map(item => {
      item.children?.map(k => {
        /**判断是否数组 */
        if (k.repel) {
          k.repel = k?.repel?.split('|');
        }
      });
    });
    let first = true;
    Object.keys(compute).map(item => {
      if (first) {
        Object.keys(compute[item]).map(k => {
          columnList.value.push({ prop: k, label: k });
        });
        first = false;
      }
      datas.value.push({ area: item, ...compute[item] });
    });
  }
  resetDatas();
}

function handleMateDelete(row) {
  const ids = row.id || ids.value;
  proxy.$modal
    .confirm('是否确认删除材质的数据项？')
    .then(function () {
      return delMate(ids);
    })
    .then(() => {
      getList();
      proxy.$modal.msgSuccess('删除成功');
    })
    .catch(() => {});
}
/**材质结束 */
/**商品价格开始 */
const price_open = ref(false);
const priceTitle = ref('');
const priceform = ref({});
const columnList = ref([
  { prop: 'area', label: '面积/数量' },
  { prop: '10', label: '10' },
  { prop: '20', label: '20' },
  { prop: '30', label: '30' },
  { prop: '40', label: '40' },
]);

const datas = ref([
  { area: '5*5', 10: '', 20: '', 30: '', 40: '' },
  { area: '10*10', 10: '', 20: '', 30: '', 40: '' },
]);

async function handlePrice(row) {
  let { code, data, msg } = await getProduct(row.id);
  if (code === 200) {
    price_open.value = true;
    priceTitle.value = `修改【${row.title}】价格`;
    priceform.value = data;
    if (!priceform.value.formula) {
      priceform.value.formula = 'price';
    }
    if (!priceform.value.calculateEnum) {
      priceform.value.calculateEnum = 0;
    }
    let compute = data.compute;
    compute = JSON.parse(compute);
    cates.value = data.productCates || [];
    columnList.value = [{ prop: 'area', label: '面积/数量' }];
    datas.value = [];
    cates.value?.map(item => {
      item.children?.map(k => {
        /**判断是否数组 */
        if (k.repel) {
          k.repel = k?.repel?.split('|');
        }
      });
    });
    let first = true;
    if (compute) {
      Object.keys(compute)?.map(item => {
        if (first) {
          Object.keys(compute[item]).map(k => {
            columnList.value.push({ prop: k, label: k });
          });
          first = false;
        }
        datas.value.push({ area: item, ...compute[item] });
      });
    }
  }
  resetDatas();
}

function resetDatas() {
  if (datas.value.length == 0) {
    columnList.value = [
      { prop: 'area', label: '面积/数量' },
      { prop: '10', label: '10' },
      { prop: '20', label: '20' },
      { prop: '30', label: '30' },
      { prop: '40', label: '40' },
    ];

    datas.value = [
      { area: '5*5', 10: '', 20: '', 30: '', 40: '' },
      { area: '10*10', 10: '', 20: '', 30: '', 40: '' },
    ];
  }
}

function priceSubmit() {
  let list = {};
  datas.value.map(item => {
    let json = { ...item };
    let key = json.area;
    delete json.area;
    delete json.row_index;
    list[key] = json;
  });
  priceform.value.compute = JSON.stringify(list);

  cates.value.map(item => {
    item.children?.map(k => {
      /**判断是否数组 */
      if (Array.isArray(k.repel)) {
        k.repel = k?.repel?.join('|');
      }
    });
  });
  proxy.$modal
    .confirm(`是否确认修改${priceform.value.title}价格？`)
    .then(function () {
      return updatePrice({ ...priceform.value, productCates: [...cates.value] });
    })
    .then(() => {
      getList();
      price_open.value = false;
      proxy.$modal.msgSuccess('修改成功');
    })
    .catch(() => {});
}
function priceCancel() {
  price_open.value = false;
}
/**商品价格结束 */

//上传图片
function uploadImg(file) {
  return new Promise((resolve, reject) => {
    const formData = new FormData();
    formData.append('file', file);
    axios
      .post('/api/upload/image', formData, {
        headers: {
          'Content-Type': 'multipart/form-data',
        },
      })
      .then(res => {
        resolve(res.data);
      })
      .catch(err => {
        reject(err);
      });
  });
}

/** 查询商品列表 */
function productChangeShow(row) {
  proxy.$modal
    .confirm(`是否确认修改${row.title}显示状态？`)
    .then(function () {
      return updateProduct({ id: row.id, isShow: !row.isShow });
    })
    .then(() => {
      getList();
      proxy.$modal.msgSuccess('修改成功');
    })
    .catch(() => {});
}

function getList() {
  loading.value = true;
  expands.value = [];
  listProduct(queryParams.value).then(response => {
    productList.value = response.rows;
    productList.value.map(item => {
      item.children = [];
    });
    total.value = response.total;
    loading.value = false;
  });
}
// 取消按钮
function cancel() {
  open.value = false;
  reset();
}
// 表单重置
function reset() {
  form.value = {
    id: null,
    title: null,
  };
  proxy.resetForm('productForm');
}
/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}
/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm('queryForm');
  handleQuery();
}
// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length !== 1;
  multiple.value = !selection.length;
}
/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = '添加商品';
}
/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const id = row.id || ids.value;
  getProduct(id).then(response => {
    form.value = response.data;
    open.value = true;
    title.value = '修改商品';
  });
}
/** 提交按钮 */
function submitForm() {
  proxy.$refs['productForm'].validate(valid => {
    if (valid) {
      if (form.value.id != null) {
        updateProduct(form.value).then(response => {
          proxy.$modal.msgSuccess('修改成功');
          open.value = false;
          getList();
        });
      } else {
        addProduct(form.value).then(response => {
          proxy.$modal.msgSuccess('新增成功');
          open.value = false;
          getList();
        });
      }
    }
  });
}
/** 删除按钮操作 */
function handleDelete(row) {
  const ids = row.id || ids.value;
  proxy.$modal
    .confirm('是否确认删除商品的数据项？')
    .then(function () {
      return delProduct(ids);
    })
    .then(() => {
      getList();
      proxy.$modal.msgSuccess('删除成功');
    })
    .catch(() => {});
}
/** 导出按钮操作 */
function handleExport() {
  proxy.download(
    'system/product/export',
    {
      ...queryParams.value,
    },
    `product_${new Date().getTime()}.xlsx`,
  );
}
getList();
</script>
