<template>
  <div>
    <el-form ref="queryFormRef" :model="queryParams" :inline="true" style="height: 65px;" @keyup.enter.native="queryList">
      <el-form-item label="单位名称">
        <el-input v-model="queryParams.unitName" placeholder="单位名称" width="120px" clearable/>
      </el-form-item>
      <el-form-item label="单位类型">
        <el-select v-model="queryParams.unitType" class="filter-item" placeholder="单位类型" width="60px" clearable>
          <el-option v-for="(key, value) in unitTypeMap" :key="key" :label="key" :value="value" />
        </el-select>
      </el-form-item>
      <el-form-item label="负责人">
        <el-input v-model="queryParams.leaderName" placeholder="单位名称" width="120px" clearable/>
      </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" :disabled="!adminFlag">新增单位</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="unitName" label="单位名称" header-align="center" width="200" />
      <el-table-column label="单位类型" header-align="center" align="center" width="120">
        <template #default="scope">
          <span :type="unitTypeMap[scope.row.unitType]">{{ unitTypeMap[scope.row.unitType] }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="unitArea" label="所属区域" header-align="center" width="120" />
      <el-table-column prop="leaderName" label="负责人" header-align="center" width="120" />
      <el-table-column prop="leaderTele" label="联系方式" header-align="center" width="120" />
      <el-table-column label="在用状态" header-align="center" align="center" width="100">
        <template #default="scope">
          <el-tag :type="mapColorMap[scope.row.useFlag]">{{ UseStateMap[scope.row.useFlag] }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="创建用水户" header-align="center" align="center" width="100">
        <template #default="scope">
          <el-tag type="success" v-if="scope.row.createUnitFalg === '1'">启用</el-tag>
          <el-tag type="danger" v-if="scope.row.createUnitFalg !== '1'">禁用</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="createMan" label="创建人" header-align="center" width="120" />
      <el-table-column prop="createUnitName" label="创建单位" header-align="center" width="120" />
      <el-table-column prop="createTime" label="创建时间" header-align="center" width="120">
        <template #default="scope">
          {{ tool.dateFormat(scope.row.createTime, "YYYY-MM-DD HH:mm:ss") }}
        </template>
      </el-table-column>
      <el-table-column prop="memo" label="备注信息" header-align="center" width="120" />

      <el-table-column label="" align="left" width="150">
        <template #default="scope" :disabled="adminFlag">
          <el-button type="text" @click="handleEdit(scope.row)" :disabled="!adminFlag">编辑</el-button>
          <el-button type="text" @click="submitDeleteForm(scope.row)" :disabled="!adminFlag">删除</el-button>
          <el-button type="text" @click="generateRegAuth(scope.row)" :disabled="!adminFlag">授权码</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- </div> -->
    <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.small" :disabled="state.disabled"
        :background="state.background" layout="total, sizes, prev, pager, next, jumper" :total="state.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="500px" draggable center>
      <el-form ref="dataFormRef" :model="formData" label-width="100px" :rules="state.rules">
        <el-form-item label="单位名称:" prop="unitName">
          <el-input v-model="formData.unitName" placeholder="单位名称" />
        </el-form-item>
        <el-form-item label="单位类型:" prop="unitType" v-if="userType==='0'">
          <el-select v-model="formData.unitType" class="filter-item" placeholder="单位类型" style="width: 350px;">
            <el-option v-for="(key, value) in unitTypeMap" :key="key" :label="key" :value="value" />
          </el-select>
        </el-form-item>
        <el-form-item label="所属区域:">
          <el-input v-model="formData.unitArea" placeholder="所属区域" width="120px" />
        </el-form-item>
        <el-form-item label="负责人员:">
          <el-input v-model="formData.leaderName" placeholder="负责人" width="120px" />
        </el-form-item>
        <el-form-item label="联系方式:">
          <el-input v-model="formData.leaderTele" placeholder="联系方式" width="120px" maxlength="11" />
        </el-form-item>
        <el-form-item label="备注信息:">
          <el-input v-model="formData.memo" type="area" 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"
            width="120px" />
        </el-form-item>
        <el-form-item label="创建用水户:" v-if="userType === '0'">
          <el-switch v-model="formData.createUnitFalg" inline-prompt="true" active-value="1" inactive-value="0"
            width="120px" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="cancel()">取消</el-button>
          <el-button type="primary" @click="submitForm" :disabled="state.dialog_disabled">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <el-dialog :title="authDialog.title" v-model="authDialog.visible" width="500px" draggable center>
      <el-form ref="dataFormRef" :model="regAuthModel" label-width="100px" :disabled="regAuthModel.authCode != null"
        :rules="state.rulesAuthor">
        <el-form-item label="单位名称:">
          <el-input v-model="formData.unitName" placeholder="单位名称" disabled />
        </el-form-item>
        <el-form-item label="授权数量:" prop="authNumber">
          <el-input v-model="regAuthModel.authNumber" placeholder="授权数量" type="number" maxlength="2" />
        </el-form-item>
        <el-form-item label="管理员:">
          <el-switch v-model="regAuthModel.adminFlag" inline-prompt="true" active-value="1" inactive-value="0" />
        </el-form-item>
        <el-form-item label="备注信息:">
          <el-input v-model="regAuthModel.memo" placeholder="备注信息" />
        </el-form-item>
        <el-form-item label="授权码:">
          <el-input v-model="regAuthModel.authCode" disabled />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="cancelAuth">关闭</el-button>
          <el-button type="primary" @click="submitAuth" :disabled="regAuthModel.authCode != null">生成</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 TAffiliatedunitAction from "@/api/customermanagement/taffiliatedunit";
import TRegAction from "@/api/customermanagement/trgeauth";
import { TAffiliatedunitQueryParam, TAffiliatedunitModel, Dialog, PageResult, TRgeAuthModel } from '@/types';
import tool from "@/until/tool"
import zhCn from 'element-plus/lib/locale/lang/zh-cn';
import { Color } from "csstype";
import { stat } from "fs";

let locale = ref(zhCn)

const dataFormRef = ref(ElForm); // 属性名必须和元素的ref属性值一致
const adminFlag = localStorage.getItem("AdminFlag")?.toString() === '1';
const userType = localStorage.getItem("UserType") || "";
const unitCode = localStorage.getItem("UnitCode") || "";

let pageSize = (localStorage.getItem("PageSize") == null ? 10 : localStorage.getItem("PageSize") as unknown as number) * 1;
type mapStatee = Record<string, string>;
const UseStateMap: mapStatee = {
  0: '停用',
  1: '使用中',
};

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

const unitTypeMap: mapStatee = {
  1: '管理单位',
  2: '管理/经销/购买',
  3: '施工/运维/售后',
  4: '使用单位'
}

const loading = ref(false)

const state = reactive({
  currentType: 0,
  queryParams: { page: 1, rows: pageSize } as TAffiliatedunitQueryParam,
  total: 0,
  small: false,
  background: false,
  disabled: false,
  dialog: {} as Dialog,
  formData: {} as TAffiliatedunitModel,
  dialog_disabled: false,
  UseStateMap,
  tableData: [] as TAffiliatedunitModel[],
  regAuthModel: {} as TRgeAuthModel,
  authDialog: {} as Dialog,
  rules: {
    unitName: [
      { required: true, message: "单位名称不能为空", trigger: "blur" }
    ],
    unitType: [
      { required: true, message: "单位类型不能为空", trigger: "blur" }
    ],
  },
  rulesAuthor: {
    authNumber: [
      { required: true, message: "授权数量不能为空", trigger: "blur" }
    ],
  },
});

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

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

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

const handleAdd = () => {
  state.currentType = 0;
  state.formData = {} as TAffiliatedunitModel;
  state.formData.useFlag='1';
  if(userType!=='0'){
    state.formData.unitType='4';
  }
  state.dialog = {
    title: '新增单位',
    visible: true,
    disabled: false,
  };
}

const handleEdit = (row: TAffiliatedunitModel) => {
  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();
  localStorage.setItem("PageSize", val.toString());
};

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

const queryList = () => {
  loading.value = true;
  //非内部用户只可查询自己创建的用水户
  if (userType !== '0') {
    queryParams.value.createUnitCode = unitCode;
  }

  TAffiliatedunitAction.QueryTAffiliatedunitList(queryParams.value).then(result => {
    if (result.status === 200) {
      const { res, flag, error } = result.data;
      if (flag === "1") {
        const pageData = res as PageResult<TAffiliatedunitModel[]>;
        state.tableData = pageData.list;
        state.total = pageData.total;
      } else {
        ElMessage.error(error);
      }
    }
    loading.value = false;
  }).catch(error => {
    //请求失败时的操作     
    ElMessage.error(error);
    loading.value = false;
  })

};

const submitForm = () => {
  dataFormRef.value.validate((valid: any) => {
    if (valid) {
      state.dialog_disabled = true;
      if (state.currentType == 0) {

        //非内部用户,创建用水户时,绑定创建单位
        state.formData.createUnitCode=userType === '0'?userType:unitCode;

        state.formData.createMan = localStorage.getItem("UserName") || "";
        TAffiliatedunitAction.AddTAffiliatedunit(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 {
        TAffiliatedunitAction.EditTAffiliatedunit(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.unitName + ']? ',
    '提示',
    {
      cancelButtonText: '取消',
      confirmButtonText: '确认',
      type: 'warning',
      center: true,
    }
  )
    .then(() => {
      TAffiliatedunitAction.DeleteTAffiliatedunit(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 TAffiliatedunitModel;
  state.dialog.visible = false;
}

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

const generateRegAuth = (row: any) => {
  let model = row as TAffiliatedunitModel;
  let auth = {} as TRgeAuthModel;

  auth.unitCode = model.unitCode;
  auth.unitType = "0";

  state.regAuthModel = auth;

  state.formData = JSON.parse(JSON.stringify(row));
  state.authDialog = {
    title: '生成授权码',
    visible: true,
    disabled: false,
  };
}

const cancelAuth = () => {
  state.authDialog = {
    title: '',
    visible: false,
    disabled: true,
  };
  state.regAuthModel = {} as TRgeAuthModel;
}

const submitAuth = () => {
  dataFormRef.value.validate((valid: any) => {
    if (valid) {
      if (state.regAuthModel.authNumber <= 0) {
        ElMessage.warning('授权数量不合法');
        return;
      }
      state.regAuthModel.createUnitCode=userType==='0'?'0':unitCode;
      
      state.regAuthModel.createMan = localStorage.getItem("UserName") || "";
      TRegAction.AddTRgeAuth(state.regAuthModel).then(result => {
        if (result.status === 200) {
          const { res, flag, error } = result.data;
          if (flag === "1") {
            state.regAuthModel = res as TRgeAuthModel;
          } else {
            ElMessage.error(error);
          }
        }
      });
    }
  });
}
</script>

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