<template>
  <div class="app-container">
    <el-row :gutter="20">
      <splitpanes :horizontal="this.$store.getters.device === 'mobile'" class="default-theme">
        <!--分类树-->
        <pane size="20">
          <el-col>
            <div class="head-container">
              <el-input
                v-model="categoryName"
                placeholder="请输入分类名称"
                clearable
                size="small"
                prefix-icon="el-icon-search"
                style="margin-bottom: 20px"
                @input="handleCategoryFilter"
              />
            </div>
            <div class="head-container">
              <el-tree
                :data="categoryTreeData"
                :props="defaultProps"
                :expand-on-click-node="false"
                :filter-node-method="filterCategoryNode"
                ref="categoryTree"
                node-key="id"
                default-expand-all
                highlight-current
                @node-click="handleCategoryNodeClick"
              />
            </div>
          </el-col>
        </pane>
        <!--物资列表-->
        <pane size="80">
          <el-col>
            <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="80px">
              <el-form-item label="物资编码" prop="materialCode">
                <el-input
                  v-model="queryParams.materialCode"
                  placeholder="请输入物资编码"
                  clearable
                  style="width: 220px"
                  @keyup.enter.native="handleQuery"
                />
              </el-form-item>
              <el-form-item label="物资名称" prop="materialName">
                <el-input
                  v-model="queryParams.materialName"
                  placeholder="请输入物资名称"
                  clearable
                  style="width: 220px"
                  @keyup.enter.native="handleQuery"
                />
              </el-form-item>
              <el-form-item label="品牌" prop="brand">
                <el-input
                  v-model="queryParams.brand"
                  placeholder="请输入品牌"
                  clearable
                  style="width: 220px"
                  @keyup.enter.native="handleQuery"
                />
              </el-form-item>
              <el-form-item label="批次号" prop="batchNo">
                <el-input
                  v-model="queryParams.batchNo"
                  placeholder="请输入批次号"
                  clearable
                  style="width: 220px"
                  @keyup.enter.native="handleQuery"
                />
              </el-form-item>
              <el-form-item>
                <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
                <el-button icon="el-icon-refresh" size="mini" @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="el-icon-plus"
                  size="mini"
                  @click="handleAdd"
                  v-hasPermi="['resource:material:add']"
                >新增</el-button>
              </el-col>
              <el-col :span="1.5">
                <el-button
                  type="danger"
                  plain
                  icon="el-icon-delete"
                  size="mini"
                  :disabled="multiple"
                  @click="handleDelete()"
                  v-hasPermi="['resource:material:remove']"
                >删除</el-button>
              </el-col>
              <right-toolbar :showSearch.sync="showSearch" @queryTable="getList" />
            </el-row>

            <el-table v-loading="loading" :data="materialList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="50" align="center" />
      <el-table-column label="序号" type="index" width="50" align="center" />
      <el-table-column label="物资编码" align="center" prop="materialCode" :show-overflow-tooltip="true" min-width="120" />
      <el-table-column label="物资名称" align="center" prop="materialName" :show-overflow-tooltip="true" min-width="150" />
      <el-table-column label="分类" align="center" prop="categoryName" :show-overflow-tooltip="true" width="120" />
      <el-table-column label="单位" align="center" prop="unit" width="80">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.material_unit" :value="scope.row.unit" />
        </template>
      </el-table-column>
      <el-table-column label="规格" align="center" prop="spec" :show-overflow-tooltip="true" width="120" />
      <el-table-column label="品牌" align="center" prop="brand" :show-overflow-tooltip="true" width="100" />
      <el-table-column label="批次号" align="center" prop="batchNo" :show-overflow-tooltip="true" width="120" />
      <el-table-column label="过期日期" align="center" prop="expireDate" width="120">
        <template slot-scope="scope">
          <span v-if="scope.row.expireDate" :style="getExpireDateStyle(scope.row.expireDate)">
            {{ parseTime(scope.row.expireDate, '{y}-{m}-{d}') }}
          </span>
          <span v-else style="color: #909399;">-</span>
        </template>
      </el-table-column>
      <el-table-column label="可重复使用" align="center" prop="reusable" width="100">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.material_reusable" :value="String(scope.row.reusable || '0')" />
        </template>
      </el-table-column>
      <el-table-column label="需要消毒" align="center" prop="sterilizeRequired" width="100">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.material_sterilize_required" :value="String(scope.row.sterilizeRequired || '0')" />
        </template>
      </el-table-column>
      <el-table-column label="报警阈值" align="center" prop="threshold" width="100">
        <template slot-scope="scope">
          <span v-if="scope.row.threshold != null">{{ scope.row.threshold }}</span>
          <span v-else style="color: #909399;">-</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="250" fixed="right" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['resource:material:edit']"
          >编辑</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-warning"
            @click="handleSetAlert(scope.row)"
            v-hasPermi="['resource:material:edit']"
          >设置报警阈值</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['resource:material:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

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

    <!-- 添加或修改物资对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="900px" append-to-body :close-on-click-modal="false">
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="物资编码" prop="materialCode">
              <el-input v-model="form.materialCode" placeholder="请输入物资编码" maxlength="50" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="物资名称" prop="materialName">
              <el-input v-model="form.materialName" placeholder="请输入物资名称" maxlength="200" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="分类" prop="categoryId">
              <treeselect
                v-model="form.categoryId"
                :options="categoryOptions"
                :normalizer="normalizer"
                :show-count="true"
                placeholder="选择分类"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="单位" prop="unit">
              <el-select
                v-model="form.unit"
                placeholder="请选择或输入单位"
                clearable
                filterable
                allow-create
                default-first-option
                style="width: 100%"
              >
                <el-option
                  v-for="dict in dict.type.material_unit"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="规格" prop="spec">
              <el-input v-model="form.spec" placeholder="请输入规格" maxlength="200" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="品牌" prop="brand">
              <el-input v-model="form.brand" placeholder="请输入品牌" maxlength="100" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="批次号" prop="batchNo">
              <el-input v-model="form.batchNo" placeholder="请输入批次号" maxlength="64" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="过期日期" prop="expireDate">
              <el-date-picker
                v-model="form.expireDate"
                type="date"
                value-format="yyyy-MM-dd"
                placeholder="选择过期日期"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="可重复使用" prop="reusable">
              <el-radio-group v-model="form.reusable">
                <el-radio
                  v-for="dict in dict.type.material_reusable"
                  :key="dict.value"
                  :label="parseInt(dict.value)"
                >{{dict.label}}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="需要消毒" prop="sterilizeRequired">
              <el-radio-group v-model="form.sterilizeRequired">
                <el-radio
                  v-for="dict in dict.type.material_sterilize_required"
                  :key="dict.value"
                  :label="parseInt(dict.value)"
                >{{dict.label}}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row v-if="form.reusable === 1">
          <el-col :span="24">
            <el-form-item label="回收政策" prop="recyclePolicy">
              <el-input v-model="form.recyclePolicy" type="textarea" placeholder="请输入回收政策" maxlength="200" :rows="2" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="报警阈值" prop="threshold">
              <el-input-number
                v-model="form.threshold"
                :min="0"
                :precision="2"
                placeholder="请输入报警阈值"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="备注" prop="remark">
              <el-input v-model="form.remark" type="textarea" placeholder="请输入备注" maxlength="500" :rows="3" />
            </el-form-item>
          </el-col>
        </el-row>
      </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="设置报警阈值" :visible.sync="alertOpen" width="500px" append-to-body :close-on-click-modal="false">
      <el-form ref="alertForm" :model="alertForm" :rules="alertRules" label-width="100px">
        <el-form-item label="报警阈值" prop="threshold">
          <el-input-number
            v-model="alertForm.threshold"
            :min="0"
            :precision="2"
            placeholder="请输入报警阈值"
            style="width: 100%"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitAlertForm">确 定</el-button>
        <el-button @click="alertOpen = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listMaterial, getMaterial, addMaterial, updateMaterial, delMaterial, setMaterialAlert } from '@/api/resource/material'
import { listCategory, treeselect } from '@/api/resource/material/category'
import Treeselect from '@riophae/vue-treeselect'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'
import { Splitpanes, Pane } from 'splitpanes'
import 'splitpanes/dist/splitpanes.css'

export default {
  name: 'ResourceMaterial',
  dicts: ['material_unit', 'material_reusable', 'material_sterilize_required'],
  components: {
    Treeselect,
    Splitpanes,
    Pane
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      materialCodes: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 物资表格数据
      materialList: [],
      // 分类树选项（用于下拉选择）
      categoryOptions: [],
      // 分类树数据（用于左侧树）
      categoryTreeData: [],
      // 分类名称（用于搜索）
      categoryName: undefined,
      // 树组件默认属性
      defaultProps: {
        children: 'children',
        label: 'categoryName'
      },
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      // 是否显示报警阈值弹出层
      alertOpen: false,
      // 表单参数
      form: {},
      // 报警阈值表单参数
      alertForm: {},
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        materialCode: undefined,
        materialName: undefined,
        categoryId: undefined,
        brand: undefined,
        batchNo: undefined
      },
      // 表单校验
      rules: {
        materialCode: [
          { required: true, message: '物资编码不能为空', trigger: 'blur' },
          { max: 50, message: '物资编码长度不能超过50个字符', trigger: 'blur' }
        ],
        materialName: [
          { required: true, message: '物资名称不能为空', trigger: 'blur' },
          { max: 200, message: '物资名称长度不能超过200个字符', trigger: 'blur' }
        ],
        categoryId: [
          { required: true, message: '分类不能为空', trigger: 'change' }
        ],
        unit: [
          { max: 16, message: '单位长度不能超过16个字符', trigger: 'blur' }
        ],
        spec: [
          { max: 200, message: '规格长度不能超过200个字符', trigger: 'blur' }
        ],
        brand: [
          { max: 100, message: '品牌长度不能超过100个字符', trigger: 'blur' }
        ],
        batchNo: [
          { max: 64, message: '批次号长度不能超过64个字符', trigger: 'blur' }
        ],
        recyclePolicy: [
          { max: 200, message: '回收政策长度不能超过200个字符', trigger: 'blur' }
        ],
        threshold: [
          { type: 'number', min: 0, message: '报警阈值不能为负数', trigger: 'blur' }
        ],
        remark: [
          { max: 500, message: '备注长度不能超过500个字符', trigger: 'blur' }
        ]
      },
      // 报警阈值表单校验
      alertRules: {
        threshold: [
          { type: 'number', min: 0, message: '报警阈值不能为负数', trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    this.getCategoryTree()
    this.getTreeselect()
    this.getList()
  },
  methods: {
    /** 查询物资列表 */
    getList() {
      this.loading = true
      listMaterial(this.queryParams).then(response => {
        this.materialList = response.rows || []
        this.total = response.total || 0
        this.loading = false
      }).catch(() => {
        this.loading = false
      })
    },
    /** 查询分类树（用于左侧树） */
    getCategoryTree() {
      listCategory({}).then(response => {
        const treeData = this.handleTree(response.data, 'id')
        // 添加"全部"选项
        this.categoryTreeData = [
          {
            id: 0,
            categoryName: '全部',
            children: treeData
          }
        ]
      })
    },
    /** 过滤分类树节点 */
    filterCategoryNode(value, data) {
      if (!value) return true
      return data.categoryName && data.categoryName.indexOf(value) !== -1
    },
    /** 处理分类树过滤 */
    handleCategoryFilter(value) {
      this.$refs.categoryTree.filter(value)
    },
    /** 分类树节点点击事件 */
    handleCategoryNodeClick(data) {
      if (data.id === 0) {
        // 点击"全部"时，清空分类筛选
        this.queryParams.categoryId = undefined
      } else {
        this.queryParams.categoryId = data.id
      }
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 转换分类数据结构 */
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children
      }
      return {
        id: node.id,
        label: node.label,
        children: node.children
      }
    },
    /** 查询分类下拉树结构 */
    getTreeselect() {
      treeselect().then(response => {
        this.categoryOptions = []
        const category = { id: 0, label: '主类目', children: [] }
        category.children = this.handleTree(response.data, 'id')
        this.categoryOptions.push(category)
      })
    },
    /** 获取过期日期样式 */
    getExpireDateStyle(expireDate) {
      if (!expireDate) return {}
      const date = new Date(expireDate)
      const now = new Date()
      const diffDays = Math.ceil((date - now) / (1000 * 60 * 60 * 24))
      if (diffDays < 0) {
        return { color: '#f56c6c' } // 已过期，红色
      } else if (diffDays <= 30) {
        return { color: '#e6a23c' } // 30天内过期，橙色
      }
      return {}
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        id: undefined,
        materialCode: undefined,
        materialName: undefined,
        categoryId: undefined,
        unit: undefined,
        spec: undefined,
        brand: undefined,
        batchNo: undefined,
        expireDate: undefined,
        reusable: 0,
        recyclePolicy: undefined,
        sterilizeRequired: 0,
        threshold: undefined,
        remark: undefined
      }
      this.resetForm('form')
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm('queryForm')
      // 重置分类筛选
      this.queryParams.categoryId = undefined
      // 清空分类树选中状态
      if (this.$refs.categoryTree) {
        this.$refs.categoryTree.setCurrentKey(null)
      }
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.materialCodes = selection.map(item => item.materialCode)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      // 如果已选择分类，默认设置分类
      if (this.queryParams.categoryId) {
        this.form.categoryId = this.queryParams.categoryId
      }
      this.open = true
      this.title = '添加物资'
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      const id = row.id || this.ids[0]
      getMaterial(id).then(response => {
        const data = response.data || {}
        this.form = {
          id: data.id,
          materialCode: data.materialCode,
          materialName: data.materialName,
          categoryId: data.categoryId,
          unit: data.unit,
          spec: data.spec,
          brand: data.brand,
          batchNo: data.batchNo,
          expireDate: data.expireDate,
          reusable: data.reusable != null ? data.reusable : 0,
          recyclePolicy: data.recyclePolicy,
          sterilizeRequired: data.sterilizeRequired != null ? data.sterilizeRequired : 0,
          threshold: data.threshold,
          remark: data.remark
        }
        this.open = true
        this.title = '编辑物资'
      })
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs['form'].validate(valid => {
        if (valid) {
          if (this.form.id != undefined) {
            updateMaterial(this.form).then(response => {
              this.$modal.msgSuccess('修改成功')
              this.open = false
              this.getList()
            })
          } else {
            addMaterial(this.form).then(response => {
              this.$modal.msgSuccess('新增成功')
              this.open = false
              this.getList()
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      let ids = this.ids;
      let curNames = [];
      if (row) {
        ids = row.id || this.ids;
        curNames.push(row.materialCode)
      } else if (this.materialCodes.length > 0) {
        curNames.push(...this.materialCodes)
      }
      const quotedNames = curNames.map(item => `“${item}”`);
      const resNames = quotedNames.join('、');
      this.$modal.confirm('是否确认删除物资编码为' + resNames + '的数据项？').then(() => {
        return delMaterial(ids)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess('删除成功')
      }).catch(() => {})
    },
    /** 设置报警阈值按钮操作 */
    handleSetAlert(row) {
      this.alertForm = {
        id: row.id,
        threshold: row.threshold || 0
      }
      this.alertOpen = true
    },
    /** 提交报警阈值表单 */
    submitAlertForm() {
      this.$refs['alertForm'].validate(valid => {
        if (valid) {
          setMaterialAlert(this.alertForm.id, this.alertForm.threshold).then(response => {
            this.$modal.msgSuccess('设置成功')
            this.alertOpen = false
            this.getList()
          })
        }
      })
    }
  }
}
</script>

<style scoped>
</style>