<template>
  <div class="vue-element-page-wrap" ref="tableContainer">
    <el-row class="page-search" justify="space-between" align="middle">
      <el-form ref="queryFormRef" :model="queryParams" :inline="true">
        <el-row :gutter="20">
          <el-col :span="6">
            <el-form-item label="" prop="params.code">
              <CustomInput
                v-model:params="queryParams.params.SITENAME"
                placeholder="工厂编码"
                clearable
                @keyUpEvent="handleQuery"
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="" prop="params.name">
              <CustomInput
                v-model:params="queryParams.params.DESCRIPTION"
                placeholder="工厂名称"
                clearable
                @keyUpEvent="handleQuery"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div class="page-search-btns">
        <el-button type="primary" @click="handleQuery">搜索</el-button>
        <el-button @click="resetQuery">重置</el-button>
      </div>
    </el-row>

    <div class="vue-element-page-table">
      <div class="page-table-operate">
        <span>更新时间：{{currentTime}}</span>
        <div class="page-table-operateBtns">
          <el-button type="primary" @click="handleAdd">
            <el-icon><Plus /></el-icon>
            创建
          </el-button>
          <el-popover :persistent="false" placement="right" popper-class="config-table-wrap" trigger="click">
            <template #reference>
              <el-button class="operateBtns-setting">
                <svg-icon icon-class="table_title" width="16px" height="16px"/>
              </el-button>
            </template>
            <ConfigTable :list="column" @updateList="updateList"/>
          </el-popover>

        </div>
      </div>
      <el-table
        border
        v-loading="loading"
        :data="pageList"
        highlight-current-row
        row-key="id"
        style="width: 100%"
      >
        <template
          v-for="(col,index) in column"
          :key="index"
        >
          <el-table-column
            v-if="!col.hide"
            :label="col.header"
            show-overflow-tooltip
          >
            <template #default="scope">
              <span v-if="col.field === 'status'">
                <span v-if="scope.row[col.field]" class="table-status-active">启用</span>
                <span v-else class="table-status-inActive">禁用</span>
              </span>
              <span v-else>{{ scope.row[col.field] }}</span>
            </template>
          </el-table-column>
        </template>

        <el-table-column
          width="160"
          label="操作"
          align="center"
          class-name="table-operation"
          fixed="right"
        >
          <template #default="scope">
            <el-button type="primary" link @click.stop="handleUpdate(scope.row)" v-if="!scope.row.status">
              编辑
            </el-button>
            <div class="splitLine" v-if="!scope.row.status"></div>
            <el-button type="danger" link @click="handleDelete(scope.row)">
              删除
            </el-button>
          </template>
        </el-table-column>
        <template v-slot:empty>
          <svg-icon icon-class="noData" width="160px" height="160px"/>
        </template>
      </el-table>
      <pagination
        v-if="total>0"
        :total="total"
        v-model:pageNumTo="queryParams.pageNum"
        v-model:pageSizeTo="queryParams.pageSize"
        @pagination="handleQuery"
      />
    </div>
    <!--  新增或编辑  -->
    <el-drawer
      :title="dialog.title"
      v-model="dialog.visible"
      @close="cancel"
      @opened="dialogOpend"
    >
      <el-form
        ref="formDataRef"
        :model="formData"
        :rules="rules"
        label-position="top"
      >

        <el-form-item label="工厂编码" prop="siteName">
          <el-input v-model="formData.siteName" placeholder="请输入角色编码" />
        </el-form-item>
        <el-form-item label="工厂名称" prop="description">
          <el-input v-model="formData.description" placeholder="请输入角色名称" />
        </el-form-item>
        <el-form-item label="地址" prop="address">
          <el-input v-model="formData.address" placeholder="请输入备注" />
        </el-form-item>

      </el-form>

      <template #footer>
        <el-button @click="cancel">取 消</el-button>
        <el-button type="primary" @click="submitForm">确 定</el-button>
      </template>
    </el-drawer>
  </div>
</template>

<script lang="ts">
export default {
  name: 'siteName'
};
</script>

<script lang="ts" setup>
import { reactive, ref, onMounted, toRefs, getCurrentInstance } from 'vue';
import {ElForm, ElMessageBox, ElTree} from 'element-plus';
import { getQueryPageList } from '@/api/common';
import { addSite, updateSite, deleteSite } from '@/api/site';

const queryFormRef = ref(ElForm);
const formDataRef = ref(ElForm);
const { proxy }: any = getCurrentInstance();

interface Tree {
  id: number
  label: string
  children?: Tree[]
}

const defaultProps = {
  children: 'children',
  label: 'label',
}
const treeRef = ref<InstanceType<typeof ElTree>>()

const state = reactive({
  queryParams: {
    queryId: 'getSiteNameList',
    version: 'web001',
    params: {
      SITENAME: '',
      DESCRIPTION: ''
    },
    pageNum: 1,
    pageSize: 10
  },
  total: 0,
  loading: false,
  pageList: [] as any,
  selectItem: undefined as any,
  dialog: {
    title: '新增工厂',
    visible: false
  },
  formData: {
    siteName: '',
    description: '',
    address: ''
  } as any,
  rules: {
    siteName: [{ required: true, message: '请输入工厂编码', trigger: 'blur' }],
    description: [{ required: true, message: '请输入工厂名称', trigger: 'blur' }],
  },
  column: [] as any,
  currentTime: '',

})
const {
  queryParams,
  total,
  loading,
  pageList,
  dialog,
  formData,
  selectItem,
  rules,
  column,
  currentTime,
} = toRefs(state);

onMounted(() => {
  state.column = [
    { header: '角色编码',field:'SITENAME',hide: false },
    { header: '角色名称',field:'DESCRIPTION',hide: false },
    { header: '地址',field:'ADDRESS',hide: false },
    { header: '创建人',field:'CREATEUSER',hide: false },
    { header: '创建时间',field:'CREATETIME',hide: false },
    { header: '更新人',field:'LASTUPDATEUSER',hide: false },
    { header: '更新时间',field:'LASTUPDATETIME',hide: false },
  ]
  // handleQuery();
});
// 更新列
function updateList(col: any) {
  state.column = col;
}
function handleQuery() {
  getQueryPageList(state.queryParams)
    .then((res:any)=>{
      console.log(res.data);
      state.pageList = res.data.list;
      state.total = res.data.total;
      showCurrentTime();
    })
    .catch(() => {});
}
function resetQuery() {
  queryFormRef.value.resetFields();
  handleQuery();
}
function showCurrentTime() {
  let date = new Date()
  state.currentTime = date.getFullYear() + '-' + (date.getMonth() + 1) + '-' + date.getDate() + ' ' + date.getHours() + ":" +
    (date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes()) + ":" + (date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds())
}


/**
 * 新增用户 dialog
 */
function handleAdd() {
  dialog.value = {
    title: '新增工厂',
    visible: true
  };
}
/**
 * 编辑用户 dialog
 */
function handleUpdate(row: any) {
  state.dialog = {
    title: '编辑角色',
    visible: true
  };

  state.selectItem = row
}

function dialogOpend() {
  formDataRef.value.resetFields();
  if(state.selectItem) {
    state.formData = {
      siteName: state.selectItem.SITENAME,
      description: state.selectItem.DESCRIPTION,
      address: state.selectItem.ADDRESS
    }
  }
}

/**
 * 取消关闭弹窗
 */
function cancel() {
  state.dialog.visible = false;
}

/**
 * 保存
 */
function submitForm() {
  formDataRef.value.validate((isValid: boolean) => {
    if (isValid) {
      if (state.selectItem) {// 编辑
        let params = {
          ...state.formData
        }

        updateSite(params).then(() => {
          proxy.$ElMessage.success('修改成功');
          cancel();
          handleQuery();
        });
      } else {
        addSite(state.formData).then((res: any) => {

          if (res.code === '0'){
            proxy.$ElMessage.success('新增成功');
          }

          cancel();
          handleQuery();
        });
      }
    }
  });
}

function handleDelete(row: any) {

  const params = {
    siteName: row.SITENAME
  } as any;
  deleteSite(params).then(() => {
    proxy.$ElMessage.success('删除成功');
    handleQuery();
  });
}

</script>
<style scoped lang="scss">

</style>
