<template>
    <div class="template_content">
        <!-- 搜索 -->
        <div class="search_box">
            <a-form layout="inline">
                <a-form-item label="企业名称">
                    <a-input
                        v-model="searchPage.enterpriseName"
                        placeholder="请输入企业名称"
                        allowClear
                    ></a-input>
                </a-form-item>
                <a-form-item label="管理员手机号">
                    <a-input
                        v-model="searchPage.adminMobile"
                        placeholder="请输入管理员手机号"
                        allowClear
                    ></a-input>
                </a-form-item>
                <a-form-item>
                    <a-button
                        type="primary"
                        icon="search"
                        @click="handlSearch"
                    >查询</a-button>
                </a-form-item>
            </a-form>
        </div>
        <!-- 表格内容 -->
        <div class="content_box">
            <!-- 表格操作 -->
            <div class="table_top">
                <a-button
                    icon="plus"
                    type="primary"
                    class="btn_right_margin"
                    @click="showModal('')"
                >添加</a-button>
            </div>
            <a-table
                :columns="columns"
                :dataSource="data"
                :loading="loading"
                :pagination="pagination"
                bordered
                size="small"
                @change="handleTableChange"
                rowKey="id"
            >

                <!-- 企业名称 -->
                <div
                    slot="name"
                    slot-scope="text,record"
                >
                    <a-row
                        type="flex"
                        justify="start"
                        align="middle"
                    >
                        <!-- 头像 -->
                        <a-col :span="4">
                            
                            <a-avatar
                                shape="square"
                                :size="64"
                                :src="record.logoUrl && record.logoUrl != '' ? record.logoUrl : ''"
                                :icon="!record.logoUrl || record.logoUrl  == '' ? 'user' : ''"
                            />
                        </a-col>
                        
                        <a-col :span="2"></a-col>
                        <!-- 企业名称 -->
                        <a-col>
                            <span style="margin: 10px;">{{record.name}}</span>
                        </a-col>
                    </a-row>
                </div>
                <!-- 用户 -->
                <div
                    slot="adminName"
                    slot-scope="text,record"
                >
                    <a-row
                        type="flex"
                        justify="start"
                        align="middle"
                    >
                        <!-- 头像 -->
                        <a-col :span="4">
                            
                            <a-avatar
                                v-if=""
                                shape="square"
                                :size="64"
                                :src="record.adminAvatarUrl && record.adminAvatarUrl != '' ? record.adminAvatarUrl : ''"
                                :icon="!record.adminAvatarUrl || record.adminAvatarUrl  == '' ? 'user' : ''"
                            />
                        </a-col>
                        <a-col :span="2"></a-col>
                        <!-- 管理员姓名、昵称，注册时间 -->
                        <a-col>
                            <a-space
                                direction="vertical"
                                align="start"
                            >
                                <span>姓名：{{record.adminName && record.adminName != '' ? record.adminName : '-'}}</span>
                                <span>昵称：{{record.adminNickName && record.adminNickName != '' ? record.adminNickName : '-'}}</span>
                                <span>注册时间：{{ timestampToymd(record.createTime) }}</span>
                            </a-space>
                            <!-- <a-row type="flex" justify="start" align="middle">
                          <a-col :span="24"><span>姓名：{{record.adminName && record.adminName != '' ? record.adminName : '-'}}</span></a-col>
                          <a-col :span="24"><span>昵称：{{record.adminNickName && record.adminNickName != '' ? record.adminNickName : '-'}}</span></a-col>
                          <a-col :span="24"><span>注册时间：{{ timestampToTime(record.createTime) }}</span></a-col>
                        </a-row> -->
                        </a-col>
                    </a-row>
                </div>
                <!-- 用户状态 -->
                <div
                    slot="adminStatus"
                    slot-scope="text,record"
                >
                    <a-tag
                        v-if="record.adminStatus == 'ENABLE'"
                        color="green"
                    >启用</a-tag>
                    <a-tag
                        v-if="record.adminStatus == 'DISABLE'"
                        color="red"
                    >禁用</a-tag>
                    <a-tag
                        v-if="record.adminStatus == 'UNACTIVATE'"
                        color="orange"
                    >未激活</a-tag>
                </div>
                <!-- 操作 -->
                <template
                    slot="action"
                    slot-scope="text, record"
                >
                    <a-button
                        icon="edit"
                        type="link"
                        @click="showModal(record)"
                    >修改</a-button>
                </template>
            </a-table>
        </div>

        <!-- Modal窗口 -->
        <template>
            <a-modal
                :visible="modalVisible"
                :title="modalTitle"
                @ok="onConfirm"
                @cancel="onCancel"
            >
                <a-form-model
                    :model="formModel"
                    :label-col="{span: 6}"
                    :wrapper-col="{span: 12}"
                    :rules="formRules"
                    ref="formModelRef"
                >
                    <a-form-model-item
                        label="企业LOGO"
                        prop="logoUrl"
                    >
                        <a-upload
                          name="avatarUpload"
                          list-type="picture-card"
                          class="avatar-uploader"
                          :show-upload-list="false"
                          :before-upload="beforeUpload"
                          @change="handleUpload"
                          :customRequest="uploadLogo"
                        >
                          <a-avatar
                            v-if="formModel.logoUrl"
                            shape="square"
                            :size="128"
                            :src="formModel.logoUrl"
                            @click="changeLogo"
                        />
                          <div v-else>
                            <a-icon :type="uploadLoading ? 'loading' : 'plus'" />
                            <div class="ant-upload-text">
                              上传
                            </div>
                          </div>
                        </a-upload>
                        <!-- <a-avatar
                            v-if=""
                            shape="square"
                            :size="64"
                            :icon="!formModel.logoUrl || formModel.logoUrl  == '' ? 'user' : ''"
                            :src="formModel.logoUrl && formModel.logoUrl != '' ? formModel.logoUrl : ''"
                            @click="changeLogo"
                        /> -->
                        
                        <!-- <a-input
                            v-model="formModel.logoUrl"
                            type="hidden"
                        > -->
                        </a-input>
                    </a-form-model-item>
                    <a-form-model-item
                        label="企业名称"
                        prop="name"
                    >
                        <a-input v-model="formModel.name">
                        </a-input>
                    </a-form-model-item>
                    <a-form-model-item
                        label="管理员手机号"
                        prop="adminMobile"
                    >
                        <a-input
                            v-model="formModel.adminMobile"
                            :disabled="modalType == 'edit'"
                        >
                        </a-input>
                    </a-form-model-item>
                    <a-form-model-item
                        label="管理员姓名"
                        prop="adminName"
                    >
                        <a-input
                            v-model="formModel.adminName"
                            :disabled="modalType == 'edit'"
                        >
                        </a-input>
                    </a-form-model-item>
                    <a-form-model-item
                        label="管理员昵称"
                        prop="adminNickName"
                    >
                        <a-input
                            v-model="formModel.adminNickName"
                            :disabled="modalType == 'edit'"
                        >
                        </a-input>
                    </a-form-model-item>
                    <a-form-model-item
                        label="省/市"
                        prop="province"
                    >
                        <area-cascader
                            v-if="showAreaSelect"
                            type="text"
                            v-model="formModel.areaSelected"
                            :data="pca"
                            placeholder=""
                        ></area-cascader>
                    </a-form-model-item>

                    <a-form-model-item
                        label="地址"
                        prop="address"
                    >
                        <a-input v-model="formModel.address">
                        </a-input>
                    </a-form-model-item>
                </a-form-model>
            </a-modal>
        </template>
    </div>
</template>
    
<script>
import { fetchList, addObj, putObj } from "@/api/biz/enterprise";
import { disposereq, timestampToTime, timestampToymd } from "@/utils/util";
import { pca, pcaa } from "area-data";
import { uploadFile } from "@/api/biz/resource";

let columns = [
  {
    title: "企业名称",
    dataIndex: "name",
    align: "center",
    scopedSlots: { customRender: "name" },
  },
  {
    title: "管理员",
    dataIndex: "adminName",
    align: "center",
    scopedSlots: { customRender: "adminName" },
  },
  {
    title: "注册手机号",
    dataIndex: "adminMobile",
    align: "center",
  },
  {
    title: "管理员状态",
    dataIndex: "adminStatus",
    align: "center",
    scopedSlots: { customRender: "adminStatus" },
    width: 100,
  },
  {
    title: "成员人数",
    dataIndex: "memberCount",
    align: "center",
    width: 80,
  },
  {
    title: "最后登陆时间",
    dataIndex: "lastLoginTime",
    align: "center",
    customRender: (text) => {
      return text ? timestampToTime(text) : "-";
    },
    width: 180,
  },
  {
    title: "操作",
    key: "action",
    scopedSlots: { customRender: "action" },
    align: "center",
    width: 90,
  },
];

export default {
  data() {
    return {
      columns: columns,
      data: [],
      searchPage: {
        pageIndex: 1,
        pageSize: 10,
        enterpriseName: "",
        adminMobile: "",
      },
      pagination: {
        showQuickJumper: true,
        showSizeChanger: true,
      },
      uploadLoading: false,
      loading: false,
      modalVisible: false,
      modalTitle: "添加",
      modalType: "add",
      formModel: {
        id: "",
        name: "",
        logoUrl: "",
        adminMobile: "",
        adminNickName: "",
        adminName: "",
        province: "",
        city: "",
        address: "",
        areaSelected: [],
      },
      formRules: {
        name: [{ required: true, message: "不能为空", trigger: "blur" }],
        adminMobile: [
          {
            required: true,
            message: "不能为空",
            trigger: "blur",
          },
          {
            pattern: /^1[3456789]\d{9}$/,
            message: "手机号格式不正确",
            trigger: "blur",
          },
        ],
      },
      pca,
      showAreaSelect: true,
    };
  },
  // 创建完毕
  created() {
    this.getList(this.searchPage);
  },
  // 即将更新渲染
  beforeUpdate() {},
  methods: {
    getList(query) {
      this.loading = true;
      fetchList(query)
        .then((res) => {
          if (res.code == 200) {
            this.data = res.data;
            let paper = { ...this.pagination };
            paper.current = query.pageIndex;
            paper.total = res.count;
            this.pagination = paper;
          } else {
            this.$message.info(res.resp_msg);
          }
          this.loading = false;
        })
        .catch((err) => {
          this.loading = false;
          disposereq(this, err);
        });
    },
    handleTableChange(pagination,filters,sorter) {
      let queryParam = { ...this.searchPage };
      queryParam.pageIndex = pagination.current;
      queryParam.pageSize = pagination.pageSize;
      this.getList(queryParam);
    },
    handlSearch() {
      let queryParam = { ...this.searchPage };
      this.getList(queryParam);
    },
    timestampToTime,
    timestampToymd,
    showModal(row) {
      // console.log(this.formModel.areaSelected)
      this.modalVisible = true;
      if (row == "") {
        this.modalTitle = "添加";
        this.modalType = "add";
      } else {
        this.modalTitle = "编辑";
        this.modalType = "edit";
        if (row.province && row.city) {
          row.areaSelected = [row.province, row.city];
        }
        this.formModel = { ...row };
      }
    },
    saveData() {
      if (this.modalType == "add") {
        let data = { ...this.formModel };
        if (data.areaSelected.length > 0) {
          data.province = data.areaSelected[0];
          data.city = data.areaSelected[1];
        }
        addObj(data)
          .then((res) => {
            if (res.resp_code == 200) {
              this.$message.info("保存成功");
              this.getList(this.searchPage);
              this.closeModal();
            } else {
              this.$message.info(res.resp_msg);
            }
          })
          .catch((err) => {
            disposereq(this, err);
          });
      } else if (this.modalType == "edit") {
        let data = { ...this.formModel };
        if (data.areaSelected.length > 0) {
          data.province = data.areaSelected[0];
          data.city = data.areaSelected[1];
        }
        putObj(data)
          .then((res) => {
            if (res.resp_code == 200) {
              this.$message.info("保存成功");
              this.getList(this.searchPage);
              this.closeModal();
            } else {
              this.$message.info(res.resp_msg);
            }
          })
          .catch((err) => {
            disposereq(this, err);
          });
      }
    },
    onConfirm() {
      this.$refs.formModelRef.validate((valid) => {
        if (valid) {
          this.saveData();
        } else {
          return false;
        }
      });
    },
    onCancel() {
      this.closeModal();
    },
    closeModal() {
      this.modalVisible = false;
      this.formModel = {
        id: "",
        name: "",
        logoUrl: "",
        adminMobile: "",
        adminNickName: "",
        adminName: "",
        province: "",
        city: "",
        address: "",
        areaSelected: [],
      };
      this.resetAreaSelected();
    },
    resetAreaSelected() {
      this.showAreaSelect = false;
      var t = setTimeout(() => {
        this.showAreaSelect = true;
      }, 0);
    },
    changeLogo() {
      console.log("changeLogo click");
    },
    beforeUpload(file) {
      const isJpgOrPng =
        file.type === "image/jpeg" || file.type === "image/png";
      if (!isJpgOrPng) {
        this.$message.info("只能上传图片");
      }
      const isLt2M = file.size / 1024 / 1024 < 10;
      if (!isLt2M) {
        this.$message.error("Image must smaller than 10MB!");
      }
      return isJpgOrPng && isLt2M;
    },
    handleUpload(info){
      if (info.file.status === "uploading") {
        this.uploadLoading = true;
        return;
      }
      if (info.file.status === 'done') {
        this.uploadLoading = false;
        return;
      }
    },
    uploadLogo(data){
    const formData = new FormData();
    formData.append("file", data.file);
    uploadFile(formData)
      .then((res) => {
        if (res.data.resp_code == 200) {
          this.formModel.logoUrl = res.data.datas.url;
        } else {
          this.$message.info("上传失败");
        }
      })
      .catch((err) => {
        disposereq(this, err);
      });
  }
  },
  
};
</script>
<style>
.template_content {
  background-color: #f0f2f5;
  width: 100%;
  height: 100%;
  box-sizing: border-box;
}
.search_box {
  width: 100%;
  box-sizing: border-box;
  padding: 14px;
  background-color: #fff;
}
.content_box {
  width: 100%;
  background-color: #fff;
  margin-top: 10px;
  padding: 14px;
}
.table_top {
  padding-bottom: 14px;
}
.btn_margin {
  margin: 0px 5px;
}
.area-select .area-selected-trigger {
  padding: 0px 0px 0px 0px;
  margin: 0px 0px 0px 10px;
}
.avatar-uploader > .ant-upload {
  width: 128px;
  height: 128px;
}
.ant-upload-select-picture-card i {
  font-size: 32px;
  color: #999;
}

.ant-upload-select-picture-card .ant-upload-text {
  margin-top: 8px;
  color: #666;
}
</style>