<template>
  <div>
    <el-form ref="queryFormRef" :model="queryParams" :inline="true">
      <el-form-item label="客户名称" v-if="userType === '0'">
        <el-input v-model="queryParams.customName" placeholder="客户名称" width="120px" />
      </el-form-item>
      <el-form-item :label="userType === '0'?'客户别名':'客户名称'">
        <el-input v-model="queryParams.otherName" placeholder="客户名称" width="120px" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" class="button" @click="queryList">查询客户</el-button>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" class="button" @click="handleAdd">新增客户</el-button>
      </el-form-item>
    </el-form>
    <el-table v-loading="loading" :data="state.tableData" border stripe style="width: 100%" :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="customName" label="客户名称" header-align="center" width="150"
        v-if="userType === '0'" />
      <el-table-column fixed prop="otherName" :label="userType === '0'?'客户别名':'客户名称'" header-align="center" width="200" />
      <el-table-column prop="customMobile" label="手机" header-align="center" width="120" />
      <el-table-column prop="authId" label="授权信息" header-align="center" width="150" />
      <el-table-column prop="createMan" label="创建人" header-align="center" width="120" />
      <el-table-column label="创建时间" header-align="center" width="160">
        <template #default="scope">
          {{ tool.dateFormat(scope.row.createTime, "YYYY-MM-DD HH:mm:ss") }}
        </template>
      </el-table-column>
      <el-table-column label="角色状态" header-align="center" align="center" width="100">
        <template #default="scope">
          <el-tag :type="mapColorMap[scope.row.useFlag]" size="small">{{ UseStateMap[scope.row.useFlag] }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="" align="left" width="180">
        <template #default="scope">
          <el-button type="text" @click="handleEdit(scope.row)">编辑</el-button>
          <el-button type="text" @click="submitDeleteForm(scope.row)">删除</el-button>
            <el-button type="text" >设备划拨</el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-config-provider :locale="locale">
      <el-pagination v-model:currentPage="queryParams.page" v-model:page-size="queryParams.rows"
        :page-sizes="[10, 15, 20, 25, 100]" :small="state.pagination.small" :disabled="state.pagination.disabled"
        :background="state.pagination.background" layout="total, sizes, prev, pager, next, jumper"
        :total="state.pagination.total" style="text-align: center;margin-top: 10px;" @size-change="handleSizeChange"
        @current-change="handleCurrentChange" />
    </el-config-provider>

    <el-dialog :title="dialog.title" v-model="dialog.visible" width="450px" draggable center>
      <el-form ref="formRef" :model="formData" label-width="100px">
        <el-form-item label="客户名称:" v-if="userType === '0'">
          <el-input v-model="formData.customName" placeholder="客户名称一" width="120px" />
        </el-form-item>
        <el-form-item label="客户名称:">
          <el-input v-model="formData.otherName" placeholder="客户名称二" width="120px" />
        </el-form-item>
        <el-form-item label="客户手机:">
          <el-input v-model="formData.customMobile" placeholder="用户手机" width="120px" />
        </el-form-item>
        <el-form-item label="在用状态:">
          <el-switch v-model="formData.useFlag" inline-prompt="true" active-value="1" inactive-value="0" active-text="使用中" inactive-text="停用"/>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="cancel()">取消</el-button>
          <el-button type="primary" @click="submitForm" :disabled="dialog.disabled">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { reactive, toRefs, ref, onMounted } from "vue";
import { ElForm, ElMessage, ElMessageBox } from 'element-plus';
import TCustomrAction from "@/api/customermanagement/tcustomr";
import { TCustomrQueryParam, TCustomrModel, Dialog, PageResult } from '@/types';
import tool from "@/until/tool"
import zhCn from 'element-plus/lib/locale/lang/zh-cn';

let locale = ref(zhCn)

const dataFormRef = ref(ElForm); // 属性名必须和元素的ref属性值一致

type mapStatee = Record<string, string>;
const UseStateMap: mapStatee = {
  0: '停用',
  1: '使用中',
};

const mapColorMap: mapStatee = {
  0: 'danger',
  1: 'success',
};

const loading = ref(false)
const userType = ref(localStorage.getItem("UserType"))
const state = reactive({
  currentType: 0,
  queryParams: { page: 1, rows: 10 } as TCustomrQueryParam,
  pagination: {
    total: 0,
    small: false,
    background: false,
    disabled: false,
  },
  dialog: { disabled: false } as Dialog,
  formData: {} as TCustomrModel,
  UseStateMap,
  tableData: [] as TCustomrModel[]
});

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

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

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

const handleAdd = () => {
  if (userType.value === "0" || userType.value === "1") {
    state.currentType = 0;
    state.formData = {} as TCustomrModel;
    state.formData.useFlag="1";
    state.dialog = {
      title: '新增客户',
      visible: true,
      disabled: false,
    };
  }
}

const handleEdit = (row: TCustomrModel) => {
  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;
  TCustomrAction.QueryTCustomrList(queryParams.value).then(result => {
    if (result.status === 200) {
      const { res, flag, error } = result.data;
      if (flag === "1") {
        const pageData = res as PageResult<TCustomrModel[]>;
        state.tableData = pageData.list;
        state.pagination.total = pageData.total;
      } else {
        ElMessage.error(error);
      }
    }
    loading.value = false;
  }).catch(error => {
    //请求失败时的操作     
    ElMessage.error(error);
    loading.value = false;
  })
};

const submitForm = () => {
  state.dialog.disabled = true;
  if (state.currentType == 0) {
    state.formData.createMan = localStorage.getItem("UserName") || "";
    TCustomrAction.AddTCustomr(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);
        }
      }
      state.dialog.disabled = false;
    });
  }
  else {
    TCustomrAction.EditTCustomr(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);
        }
      }
      state.dialog.disabled = false;
    });
  }
};

const submitDeleteForm = (row: any) => {
  ElMessageBox.confirm(
    ' 是否删除客户[' + row.userName + ']? ',
    '提示',
    {
      cancelButtonText: '取消',
      confirmButtonText: '确认',
      type: 'warning',
      center: true,
    }
  )
    .then(() => {
      TCustomrAction.DeleteTCustomr(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 = () => {
  state.formData = {} as TCustomrModel;
  state.dialog.visible = false;
}

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

  queryList();
})
</script>

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