<template>
  <div class="app-container-page">
    <el-form class="table-form-search" :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch"
      label-width="100px">
      <el-row>
        <el-col :span="8">
          <el-form-item label="物料名称" prop="materialName">
            <el-input v-model="queryParams.materialName" placeholder="请输入物料名称" clearable @keyup.enter="handleQuery" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="物料简称" prop="materialShortName">
            <el-input v-model="queryParams.materialShortName" placeholder="请输入物料简称" clearable
              @keyup.enter="handleQuery" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="物料编码" prop="materialCode">
            <el-input v-model="queryParams.materialCode" placeholder="请输入物料编码" clearable @keyup.enter="handleQuery" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="8">
          <el-form-item label="物料类型" prop="typeId">
            <el-cascader :options="materTypeList" style="width: 100%;" v-model="queryParams.typeId" :props="{
              children: 'children',
              label: 'typeName',
              value: 'id',
            }" placeholder="请选择物料类型" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="物料单位" prop="unitId">
            <el-select v-model="queryParams.unitId" placeholder="请选择物料单位" clearable>
              <el-option v-for="dict in materUnitList" :key="dict.id" :label="dict.unitName" :value="dict.id" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24" class="searchBtn">
          <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-col>
      </el-row>
    </el-form>

    <div class="table-list">
      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button type="primary" plain icon="Plus" @click="handleAdd"
            v-hasPermi="['worn:material:add']">新增</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete"
            v-hasPermi="['worn:material:remove']">删除</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button type="warning" plain icon="Download" @click="handleExport"
            v-hasPermi="['worn:material:export']">导出</el-button>
        </el-col>
        <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
      </el-row>

      <el-table v-loading="loading" :data="materialList" @selection-change="handleSelectionChange" show-overflow-tooltip
        border>
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="序号" align="center" prop="id" width="70" />
        <el-table-column label="物料名称" align="center" prop="materialName" />
        <el-table-column label="物料简称" align="center" prop="materialShortName" />
        <el-table-column label="物料编码" align="center" prop="materialCode" />
        <el-table-column label="物料单位" align="center" prop="unitName" />
        <el-table-column label="公斤转换系数" align="center" prop="kgFactor" width="150" />
        <el-table-column label="物料类别" align="center" prop="typeParentNames" />
        <el-table-column label="物料类型" align="center" prop="typeName" />
        <el-table-column label="规格" align="center" prop="specification" />
        <el-table-column label="型号" align="center" prop="model" />
        <el-table-column label="条形码" align="center" prop="barcode" />
        <el-table-column label="重量(kg)" align="center" prop="weight" />
        <el-table-column label="描述" align="center" prop="description" />
        <el-table-column label="状态" align="center" prop="status">
          <template #default="scope">
            <dict-tag :options="dictTagData()" :value="scope.row.status" />
          </template>
        </el-table-column>
        <el-table-column label="操作" fixed="right" align="center" width="150">
          <template #default="scope">
            <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)"
              v-hasPermi="['worn:material:edit']">修改</el-button>
            <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)"
              v-hasPermi="['worn:material: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" />
    </div>

    <!-- 添加或修改物料对话框 -->
    <el-dialog :title="title" v-model="open" width="1000px" append-to-body>
      <el-form ref="materialRef" :model="form" :rules="rules" label-width="80px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="物料名称" prop="materialName">
              <el-input v-model="form.materialName" placeholder="请输入物料名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="物料简称" prop="materialShortName">
              <el-input v-model="form.materialShortName" placeholder="请输入物料简称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="物料编码" prop="materialCode">
              <el-input v-model="form.materialCode" :disabled="true" placeholder="编码代码自动生成" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="物料类型" prop="typeId">
              <el-cascader :options="materTypeList" style="width: 100%;" v-model="form.typeId" :props="{
                children: 'children',
                label: 'typeName',
                value: 'id',
              }" placeholder="请选择物料类型" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="物料单位" prop="unitId">
              <el-select v-model="form.unitId" placeholder="请选择物料单位" clearable>
                <el-option v-for="dict in materUnitList" :key="dict.id" :label="dict.unitName" :value="dict.id" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="规格" prop="specification">
              <el-input v-model="form.specification" placeholder="请输入规格" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="型号" prop="model">
              <el-input v-model="form.model" placeholder="请输入型号" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="条形码" prop="barcode">
              <el-input v-model="form.barcode" placeholder="请输入条形码" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="重量(kg)" prop="weight">
              <el-input v-model="form.weight" placeholder="请输入单件重量(kg)" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="状态" prop="status">
              <el-radio v-model="form.status" label="0">启用</el-radio>
              <el-radio v-model="form.status" label="1">停用</el-radio>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="描述" prop="description">
              <el-input v-model="form.description" type="textarea" placeholder="请输入内容" />
            </el-form-item>
          </el-col>
        </el-row>
      </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="Material">
import { listMaterial, getMaterial, delMaterial, addMaterial, updateMaterial, getMaterTypeTree } from "@/api/worn/material"
import { listUnit } from "@/api/worn/unit"

const { proxy } = getCurrentInstance()

const ids = ref([])
const materialList = ref([])

const open = ref(false)
const loading = ref(true)
const multiple = ref(true)
const showSearch = ref(true)


const total = ref(0)
const title = ref("")

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    materialName: null,
    materialShortName: null,
    materialCode: null,
    typeId: null,
    unitId: null,
  },
  rules: {
    materialName: [
      { required: true, message: "物料名称不能为空", trigger: "blur" }
    ],
    typeId: [
      { required: true, message: "物料类型不能为空", trigger: "blur" }
    ],
    unitId: [
      { required: true, message: "物料单位不能为空", trigger: "blur" }
    ],
  }
})

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

/** 查询物料列表 */
function getList() {
  loading.value = true
  listMaterial(queryParams.value).then(response => {
    materialList.value = response.rows
    total.value = response.total
    loading.value = false
  })
}

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

// 表单重置
function reset() {
  form.value = {
    materialName: null,
    materialShortName: null,
    materialCode: null,
    typeId: null,
    unitId: null,
  }
  proxy.resetForm("materialRef")
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  if (queryParams.value.typeId) {
    queryParams.value.typeId = queryParams.value.typeId[queryParams.value.typeId.length - 1]
  }
  getList()
}

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

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

/** 新增按钮操作 */
function handleAdd() {
  reset()
  open.value = true
  title.value = "添加物料"
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset()
  const _id = row.id || ids.value
  getMaterial(_id).then(response => {
    form.value = response.data
    open.value = true
    title.value = "修改物料"
  })
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["materialRef"].validate(valid => {
    if (valid) {
      if (form.value.id != null) {
        form.value.typeId = form.value.typeId[form.value.typeId.length - 1]
        updateMaterial(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功")
          open.value = false
          getList()
        })
      } else {
        form.value.typeId = form.value.typeId[form.value.typeId.length - 1]
        addMaterial(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功")
          open.value = false
          getList()
        })
      }
    }
  })
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value
  proxy.$modal.confirm('是否确认删除物料编号为"' + _ids + '"的数据项？').then(function () {
    return delMaterial(_ids)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => { })
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('worn/material/export', {
    ...queryParams.value
  }, `物料管理_${new Date().getTime()}.xlsx`)
}

// 物料类型下拉获取相关
const materTypeList = ref([]);
function getMaterTypeTreeFun() {
  getMaterTypeTree().then((response) => {
    materTypeList.value = response.data;
  });
}
getMaterTypeTreeFun();

// 物料单位
const materUnitList = ref([]);
function getMaterUnitFn() {
  listUnit().then((res) => {
    materUnitList.value = res.rows;
  })
}
getMaterUnitFn();
// 物资类型状态 (0正常1停用) - 状态按钮暂未显示
const statusList = ref([
  { value: 0, label: "启用", elTagType: "success", elTagClass: null },
  { value: 1, label: "停用", elTagType: "warning", elTagClass: null }
]);
const dictTagData = () => {
  return statusList.value.map((item) => ({
    ...item,
    value: String(item.value),
  }));
};
getList()
</script>
