<template>
  <div>
    <el-form ref="queryFormRef" :model="queryParams" :inline="true">
      <el-form-item label="库房名称:">
        <el-input v-model="queryParams.stkroomName" placeholder="库房名称" width="120px" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" class="button" :disabled="state.search_disabled" @click="queryList">查询库房</el-button>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" class="button" :disabled="!adminFlag" @click="handleAdd">新增库房</el-button>
      </el-form-item>
    </el-form>
    <!-- <div class="wrapper"> -->
    <el-table v-loading="loading" :data="state.tableData" border stripe style="width: 100%;margin-top: -15px;" :height="tableHeight"
      highlight-current-row @current-change="handleCurrentRowChange"
      :header-cell-style="{ background: '#606266', color: '#FFFFFF' }">
      <el-table-column fixed type="index" width="50" align="center" />
      <el-table-column fixed prop="stkroomName" label="库房名称" header-align="center" width="120" />
      <el-table-column prop="stkroomPy" label="拼音码" header-align="center" width="120" />
      <el-table-column prop="memo" label="备注" header-align="center" width="150" />
      <el-table-column align="center" width="100">
        <template #default="scope">
          <el-button type="text" @click="handleEdit(scope.row)">编辑</el-button>
          <el-button type="text" @click="submitDeleteForm(scope.row)" :disabled="!adminFlag">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- </div> -->

    <el-dialog :title="dialog.title" v-model="dialog.visible" width="450px" draggable center>
      <el-form ref="dataFormRef" :model="formData" label-width="100px" :rules="state.rules">
        <el-form-item label="库房名称:" prop="stkroomName">
          <el-input v-model="formData.stkroomName" placeholder="库房名称" width="120px" />
        </el-form-item>
        <el-form-item label="拼音码:" prop="loginId">
          <el-input v-model="formData.stkroomPy" placeholder="拼音码" width="120px" />
        </el-form-item>
        <el-form-item label="备注:">
          <el-input v-model="formData.memo" type="textarea" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="cancel()">取消</el-button>
          <el-button type="primary" @click="submitForm">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { reactive, toRefs, toRef, ref, onMounted } from "vue";
import { ElForm, ElMessage, ElMessageBox } from 'element-plus';
import DicStkroomAction from "@/api/systemdictionary/stkroom";
import { DicStkroomModel, DicStkroomModelQueryParam, Dialog, PageResult } from '@/types';

import zhCn from 'element-plus/lib/locale/lang/zh-cn';

let locale = ref(zhCn)

const queryFormRef = ref(ElForm); // 属性名必须和元素的ref属性值一致
const dataFormRef = ref(ElForm); // 属性名必须和元素的ref属性值一致
let userId = localStorage.getItem("CustomerId") + '';
const adminFlag = localStorage.getItem("AdminFlag")?.toString() === '1';

const loading = ref(false)

const state = reactive({
  currentType: 0, //0 新增 1 编辑
  search_disabled: false,
  queryParams: { page: 1, rows: 10 } as DicStkroomModelQueryParam,
  pagination: {
    total: 0,
    small: false,
    background: false,
    disabled: false,
  },
  dialog: {} as Dialog,
  formData: {} as DicStkroomModel,
  tableData: [] as DicStkroomModel[],
  rules: {
    stkroomName: [{ required: true, message: "库房名称不能为空", trigger: "blur", },]
  },
});

const {
  queryParams,
  dialog,
  formData,
  tableData,
  pagination
} = toRefs(state);

const tableHeight = ref(document.documentElement.clientHeight - 220);
const currentRow = ref()

const handleCurrentRowChange = (val: DicStkroomModel | undefined) => {
  currentRow.value = val
}

async function handleAdd() {
  state.currentType = 0;
  state.formData = {} as DicStkroomModel;
  state.dialog = {
    title: '新增库房',
    visible: true,
    disabled: false,
  };
}

async function handleEdit(row: any) {
  state.currentType = 1;
  state.formData = JSON.parse(JSON.stringify(row));;
  state.dialog = {
    title: '编辑库房',
    visible: true,
    disabled: false,
  };
}

const handleSizeChange = (val: number) => {
  queryParams.value.rows = val;
  queryList();
};

const handleCurrentChange = (val: number) => {
  queryParams.value.page = val;
  queryList();
};

const queryList = () => {
  loading.value = true;
  state.search_disabled = true;
  DicStkroomAction.QueryDicStkroomList(queryParams.value).then(result => {
    if (result.status === 200) {
      const { res, flag, error } = result.data;
      if (flag === "1") {
        state.tableData = res as DicStkroomModel[];
      } else {
        ElMessage.error(error || "查询异常...");
      }
      loading.value = false;
      state.search_disabled = false;
    }
  }).catch(error => {
    //请求失败时的操作     
    ElMessage.error(error || "未知异常...");
    loading.value = false;
    state.search_disabled = false;
  })

};

const submitForm = () => {
  dataFormRef.value.validate((valid: any) => {
    if (valid) {
      if (state.currentType == 0) {
        DicStkroomAction.AddDicStkroom(state.formData).then(result => {
          if (result.status === 200) {
            const { res, flag, error } = result.data;
            if (flag === "1") {
              ElMessage.success('新增成功');
              cancel();
              queryList();
            } else {
              ElMessage.error(error || "新增异常...");
            }
          }
        });
      }
      else if (state.currentType == 1) {
        DicStkroomAction.EditDicStkroom(state.formData).then(result => {
          if (result.status === 200) {
            const { res, flag, error } = result.data;
            if (flag === "1") {
              ElMessage.success('编辑成功');
              cancel();
              queryList();
            } else {
              ElMessage.error(error || "编辑异常...");
            }
          }
        });
      }
    }
  });
};

const submitDeleteForm = (row: DicStkroomModel) => {
  ElMessageBox.confirm(
    ' 是否删除库房[' + row.stkroomName + ']? ',
    '提示',
    {
      cancelButtonText: '取消',
      confirmButtonText: '确认',
      type: 'warning',
      center: true,
    }
  )
    .then(() => {
      DicStkroomAction.DeleteDicStkroom(row.id).then(result => {
        if (result.status === 200) {
          const { res, flag, error } = result.data;
          if (flag === "1") {
            ElMessage.success('删除成功');
            queryList();
          } else {
            ElMessage.error(error || "删除异常...");
          }
        }
      });
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '取消删除成功!',
      })
    })
};

const cancel = () => {
  dataFormRef.value.resetFields();
  state.formData = {} as DicStkroomModel;
  state.dialog.visible = false;
}

onMounted(() => {
  window.onresize = function () {
    tableHeight.value = document.documentElement.clientHeight - 220
  }

  queryList();
})
</script>

<style lang="scss" scoped>
.button {
  margin: 10px 0;
}
</style>