<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="时间" prop="xhTime">
        <el-date-picker clearable
                        v-model="queryParams.xhTime"
                        type="date"
                        value-format="YYYY-MM-DD"
                        placeholder="请选择时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="规格" prop="xhType">
        <el-select
            v-model="queryParams.xhType"
            placeholder="请选择规格"
            clearable
            @change="handleSpecChange" style="width: 150px;">
          <el-option
              v-for="item in specOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="供方" prop="xhClass">
        <el-select
            v-model="queryParams.xhClass"
            placeholder="请选择供方"
            clearable
            :disabled="!queryParams.xhType" style="width: 150px;">
          <el-option
              v-for="item in supplierOptions"
              :key="item"
              :label="item"
              :value="item">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="价格" prop="price">
        <el-input
            v-model="queryParams.price"
            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"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="success"
            plain
            icon="Edit"
            :disabled="single"
            @click="handleUpdate"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="danger"
            plain
            icon="Delete"
            :disabled="multiple"
            @click="handleDelete"
        >删除</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="xhList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
<!--      <el-table-column label="ID" align="center" prop="xhId" />-->
      <el-table-column label="时间" align="center" prop="xhTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.xhTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="规格" align="center" prop="xhType" />
      <el-table-column label="供方" align="center" prop="xhClass" />
      <el-table-column label="价格" align="center" prop="price" />
      <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)">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)">删除</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="500px" append-to-body>
      <el-form ref="xhRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="时间" prop="xhTime">
          <el-date-picker clearable
                          v-model="form.xhTime"
                          type="date"
                          value-format="YYYY-MM-DD"
                          placeholder="请选择时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="规格" prop="xhType">
          <el-select
              v-model="form.xhType"
              placeholder="请选择规格"
              @change="handleFormSpecChange">
            <el-option
                v-for="item in specOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="供方" prop="xhClass">
          <el-select
              v-model="form.xhClass"
              placeholder="请选择供方"
              :disabled="!form.xhType">
            <el-option
                v-for="item in formSupplierOptions"
                :key="item"
                :label="item"
                :value="item">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="价格" prop="price">
          <el-input v-model="form.price" 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="Xh">
import { listXh, getXh, delXh, addXh, updateXh } from "@/api/lean/xh";

const { proxy } = getCurrentInstance();

const xhList = 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 specOptions = ref([
  { value: '120D/120f', label: '120D/120f' },
  { value: '150D/096f', label: '150D/096f' },
  { value: '150D/120f', label: '150D/120f' },
  { value: '150D/144f', label: '150D/144f' },
  { value: '200D/096f', label: '200D/096f' },
  { value: '200D/144f', label: '200D/144f' },
  { value: '250D/120f', label: '250D/120f' },
  { value: '300D/144f', label: '300D/144f' },
  { value: '450D/192f', label: '450D/192f' }
]);

// 供方选项（根据规格动态变化）
const supplierOptions = ref([]);
const formSupplierOptions = ref([]);

// 规格与供方的映射关系
const specSupplierMap = {
  '120D/120f': ['盛虹202dtex/120f', '盛元220dtex/120f'],
  '150D/096f': ['恒通298dtex/096f', '盛虹263dtex/096f', '盛元275dtex/096f'],
  '150D/120f': ['盛虹268dtex/120f', '盛元275dtex/120f'],
  '150D/144f': ['恒通272dtex/144f', '盛虹265dtex/144f', '盛元272dtex/144f'],
  '200D/096f': ['恒通378dtex/096f', '恒逸378dtex/096f', '盛虹368dtex/096f', '盛元365dtex/096f'],
  '200D/144f': ['恒通378dtex/144f', '盛虹363dtex/144f', '盛元365dtex/144f'],
  '250D/120f': ['恒通478dtex/122f', '恒逸478dtex/120f', '盛虹465dtex/120f'],
  '300D/144f': ['恒通545dtex/144f', '恒逸560dtex/144f', '盛虹575dtex/144f'],
  '450D/192f': ['恒通758dtex/192f']
};

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    xhTime: null,
    xhType: null,
    xhClass: null,
    price: null,
    orderByColumn: "xh_time",
    isAsc: "descending"
  },
  rules: {
  }
});

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

/** 处理规格变化 */
function handleSpecChange(spec) {
  if (spec && specSupplierMap[spec]) {
    supplierOptions.value = specSupplierMap[spec];
    // 如果当前选择的供方不在新选项中，则清空供方选择
    if (queryParams.value.xhClass && !supplierOptions.value.includes(queryParams.value.xhClass)) {
      queryParams.value.xhClass = null;
    }
  } else {
    supplierOptions.value = [];
    queryParams.value.xhClass = null;
  }
}

/** 处理表单中规格变化 */
function handleFormSpecChange(spec) {
  if (spec && specSupplierMap[spec]) {
    formSupplierOptions.value = specSupplierMap[spec];
    // 如果当前选择的供方不在新选项中，则清空供方选择
    if (form.value.xhClass && !formSupplierOptions.value.includes(form.value.xhClass)) {
      form.value.xhClass = null;
    }
  } else {
    formSupplierOptions.value = [];
    form.value.xhClass = null;
  }
}

/** 查询现货价格列表 */
function getList() {
  loading.value = true;
  listXh(queryParams.value).then(response => {
    xhList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

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

// 表单重置
function reset() {
  form.value = {
    xhId: null,
    xhTime: null,
    xhType: null,
    xhClass: null,
    price: null
  };
  formSupplierOptions.value = [];
  proxy.resetForm("xhRef");
}

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

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

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

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加现货价格";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _xhId = row.xhId || ids.value
  getXh(_xhId).then(response => {
    form.value = response.data;
    // 初始化供方选项
    if (form.value.xhType && specSupplierMap[form.value.xhType]) {
      formSupplierOptions.value = specSupplierMap[form.value.xhType];
    }
    open.value = true;
    title.value = "修改现货价格";
  });
}

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

/** 删除按钮操作 */
function handleDelete(row) {
  const _xhIds = row.xhId || ids.value;
  proxy.$modal.confirm('是否确认删除现货价格编号为"' + _xhIds + '"的数据项？').then(function() {
    return delXh(_xhIds);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {});
}

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

getList();
</script>
