<template>
  <div class="h-full">
    <div class="search flex justify-between bg-white rounded-md">
      <el-form :inline="true" class="demo-form-inline" size="default">
        <el-form-item>
          <el-cascader :props="propsSearch" :options="proviceList" v-model="area_id" @change="handleChange" />
        </el-form-item>
      </el-form>
      <div>
        <el-button type="primary" @click="area_id = []"> 清空 </el-button>
        <el-button type="primary" @click="initData"> 查询 </el-button>
      </div>
    </div>
    <div class="bg-white rounded-md mt-4 px-23px py-16px">
      <div class="flex justify-between pb-4">
        <div>
          <el-button type="primary" @click="addData">新增</el-button>
          <el-button type="primary" @click="exportData">导出</el-button>
          <import-button url="/school/main" @success="initData">
            <template #text>批量导入</template>
          </import-button>
          <el-button type="danger" @click="deleteMul" :disabled="multipleSelection.length == 0">删除</el-button>
        </div>
        <div class="flex content-center">
          <el-input v-model="keyword" class="w-40 mx-2" size="small" placeholder="请输搜索关键词" :suffix-icon="Search" clearable
            @clear="initData" />
          <el-button type="primary" @click="initData">查询</el-button>
        </div>
      </div>
      <div class="tableList">
        <div class="tableDiv my-20px">
          <el-table :data="tableData" @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="55" />
            <el-table-column prop="id" label="序号" width="100"></el-table-column>
            <el-table-column prop="sm_name" label="学校名称" show-overflow-tooltip></el-table-column>
            <el-table-column prop="sm_address" label="学校地址" show-overflow-tooltip></el-table-column>
            <el-table-column prop="sm_lxr_contact" label="联系电话" show-overflow-tooltip></el-table-column>
            <el-table-column prop="sm_email" label="邮箱" show-overflow-tooltip></el-table-column>
            <el-table-column label="操作" width="245">
              <template #default="scope">
                <el-button type="text" @click="detailData(scope.row)">详情</el-button><el-divider direction="vertical" />
                <el-button type="text" @click="editData(scope.row)">编辑</el-button><el-divider direction="vertical" />
                <el-button type="text" @click="deleteItem(scope.row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
        <div class="flex justify-end">
          <el-pagination v-model:current-page="form_query.page" v-model:page-size="form_query.limit"
            :page-sizes="[6, 12, 18, 50]" :pager-count="5" :small="true" layout="total,sizes, prev, pager, next, jumper"
            :total="total" @size-change="handleSizeChange" @current-change="handleCurrentChange" />
        </div>
      </div>
    </div>
    <el-dialog v-model="dialogVisible" :title="title" width="780px">
      <el-form ref="ruleFormRef" :model="ruleForm" :rules="rules" label-width="120px" class="demo-ruleForm"
        :size="formSize" status-icon>
        <el-form-item label="学校logo" prop="sm_logo">
          <file-upload-progress v-model:part="ruleForm.sm_logo" :limit="1" class="w-520px" accept=".jpg,.jpeg,.webp,.png"
            :size-limit="2 * 1024 * 1024" ::key="nowTime">
            <template #default>
              <div class="
                                  flex_center
                                  w-65px
                                  h-65px
                                  border border-dashed border-hex-E4E6E8
                                  bg-hex-F9F9F9
                                  text-hex-9D9AB9
                                ">
                <i-akar-icons:plus class="text-xl" />
              </div>
            </template>
            <template #tip>
              <div class="mt-2 text-xs">
                支持格式：jpg,png,jpeg（2M以内） 建议尺寸1:1
              </div>
            </template>
          </file-upload-progress>
        </el-form-item>
        <div class="flex">
          <el-form-item label="学校名称" prop="sm_name">
            <el-input v-model="ruleForm.sm_name" />
          </el-form-item>
          <el-form-item label="学校电话" prop="sm_lxr_contact">
            <el-input v-model="ruleForm.sm_lxr_contact" />
          </el-form-item>
        </div>
        <div class="flex">
          <el-form-item label="级别" prop="sm_period">
            <el-select v-model="ruleForm.sm_period">
              <el-option v-for="g in xdList" :key="g.v" :label="g.n" :value="g.v"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="学校地址" prop="sm_address">
            <el-cascader :props="props" :options="proviceList" v-model="ruleForm.sm_address" @change="handleChange" />
          </el-form-item>
        </div>
        <div class="flex">
          <el-form-item label="邮箱" prop="sm_email">
            <el-input class="rank" v-model="ruleForm.sm_email" />
          </el-form-item>
          <el-form-item label="详细地址" prop="detail_area">
            <el-input class="rank" v-model="ruleForm.detail_area" />
          </el-form-item>
        </div>
        <el-form-item label="学校风采" prop="sm_brief">
          <TinymceVue v-if="dialogVisible" class="w-520px" v-model="ruleForm.sm_brief"></TinymceVue>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer mx-auto center">
          <el-button type="primary" :disabled="isButton" @click="submitForm(ruleFormRef)">
            确定 </el-button><el-button @click="dialogVisible = false">取消</el-button>
        </div>
      </template>
    </el-dialog>
    <el-dialog v-model="detailVisible" title="详情" width="680px">
      <el-divider border-style="dotted" />
      <div class="margin_center">
        <div class="flex justify-center">
          <img v-if="detailInfo.sm_logo" class="w-146px mr-4" :src=" getFullUrl(detailInfo.sm_logo)" alt="" />
          <div>
            <h3 class="text-lg font-medium text-black">
              {{ detailInfo.sm_name }}
            </h3>
            <p class="text-xs text-gray-500">
              <span class="mr-3">{{ detailInfo.sm_period }}</span>
              {{ detailInfo.sm_area_id1_name }}{{ detailInfo.sm_area_id2_name }}{{ detailInfo.sm_area_id3_name }}
            </p>
            <div class="text-sm font-medium text-black mt-3">
              <p>详细地址：{{ detailInfo.sm_address }}</p>
              <p>学校电话：{{ detailInfo.sm_lxr_contact }}</p>
            </div>
          </div>
        </div>
        <el-divider border-style="dotted" />
        <div v-html="detailInfo.sm_brief" class="text-center"></div>
      </div>
      <div class="text-center">
        <el-button type="primary" :disabled="isButton" @click="detailVisible = false">
          返回
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import {
  Search,
  Delete,
  Download,
  Plus,
  ZoomIn,
} from "@element-plus/icons-vue";
import { ElMessage } from "element-plus";
import _, { endsWith, toString } from "lodash";
import { ref, nextTick } from "vue";
import { useRouter } from "vue-router";
let https = window.GLOBAL_CONFIG.api;
// const nextTick = nextTick();
const router = useRouter();
let grade = $ref("");
let area_id = $ref([]);
let gradeData = $ref([
]);
let xdList = $ref([]);
request({
  url: "/common/sjzd/option",
  data: {
    cs_code: "XD",
  },
}).then((res) => {
  if (res.code == "1") {
    xdList = res.data.option;
  }
});
let keyword = $ref("");
let nowTime = Date.now();
let tableData = $ref([]);
let multipleSelection = $ref([]);
let importVisible = $ref(false);
const handleSelectionChange = (val) => {
  multipleSelection = [];
  val.forEach((i) => {
    multipleSelection.push(i.id);
  });
};

// const getContent = (v) => {
//   console.log(v,11111111);
//   ruleForm.sm_brief = v
// }

function handleSizeChange(val) {
  form_query.limit = val;
  form_query.page = 1;
  initData();
}
let total = $ref(10);
const form_query = $ref({
  page: 1,
  limit: 6,
});
initData();
function initData() {
  let data = {
    ...form_query,
    keyword,
    sm_area_id1: area_id.length >= 1 ? area_id[0] : '',
    sm_area_id2: area_id.length >= 2 ? area_id[1] : '',
    sm_area_id3: area_id.length === 3 ? area_id[2] : '',
  };
  request({
    url: "/school/main/index",
    data,
  }).then((res) => {
    if (res.code == "1") {
      tableData = res.data.page_data;
      total = Number(res.data.total_rows);
    }
  });
}

function handleCurrentChange(val) {
  form_query.page = val;
  initData();
}

let ruleFormRef = $ref();
let ruleForm = $ref({
  sm_name: "",
  sm_lxr_contact: "",
  sm_logo: "",
  sm_address: [],
  sm_period: "",
  detail_area: "",
  sm_email: "",
  sm_brief: "",
  sm_address_detail: '',
});

// function handleUpdate(data){
//   ruleForm.sm_brief = data
//   console.log(data,'update');
// }
const rules = $ref({
  sm_name: [
    {
      required: true,
      message: "请填写学校名称",
      trigger: "submit",
    },
  ],
  sm_lxr_contact: [
    { required: true, message: "请填写学校电话", trigger: "submit" },
  ],
  sm_logo: [{ required: true, message: "请上传logo图片", trigger: "submit" }],
  sm_period: [{ required: true, message: "请选择学校级别", trigger: "submit" }],
  sm_address: [
    { required: true, message: "请选择学校地址", trigger: "submit" },
  ],
  detail_area: [
    { required: true, message: "请输入详细地址", trigger: "submit" },
  ],
  sm_brief: [{ required: true, message: "请填写学校风采", trigger: "submit" }],
});
let dialogVisible = $ref(false);
let title = $ref("");
let isEdit = $ref(false);
let tiny_id = $ref('xxfc0')
// 新增弹窗
function addData() {
  dialogVisible = true;
  title = "新增";
  isEdit = false;
  Object.keys(ruleForm).find((item) => {
    ruleForm[item] = "";
  });
  tiny_id = 'xxfc0'
}

let proviceList = $ref([]);
request({
  url: "/common/district/search",
  data: {
    upid: 0,
  },
}).then((res) => {
  if (res.code == "1") {
    proviceList = res.data.page_data;
  }
});

let address_name = [];
function getArea(id) {
  request({
    url: "/common/district/detail",
    data: {
      id: id,
    },
  }).then((res) => {
    if (res.code == "1") {
      address_name.push(res.data.one_info.name);
      console.log(address_name);
    }
  });
}
async function handleChange(val) {
  console.log(ruleForm.sm_address, 'rule');
  console.log(val, 'val');
  address_name = [];
  let name = '';
  for (var key in val) {
    await request({
      url: "/common/district/detail",
      data: {
        id: val[key],
      },
    }).then((res) => {
      if (res.code == "1") {
        address_name.push(res.data.one_info.name);
        console.log(address_name);
      }
    }).catch(err => {
      console.log(err);
    });
  }
}

// 地址级联
let address = $ref("");
let props = {
  value: "id",
  label: "name",
  lazy: true,
  lazyLoad(node, resolve) {
    const { level } = node;
    let nodes = [];
    let data = {
      upid: node.value,
    };
    if (node.value * 1 >= 32 && node.value * 1 <= 36) {
      request({
        url: "/common/district/search",
        data,
      }).then((res) => {
        if (res.code == "1") {
          res.data.page_data.map((item) => {
            let obj = {
              id: item.id,
              name: item.name,
              leaf: node.level >= 1,
            };
            nodes.push(obj);
          });
          resolve(nodes);
        }
      });
    } else {
      request({
        url: "/common/district/search",
        data,
      }).then((res) => {
        if (res.code == "1") {
          res.data.page_data.map((item) => {
            let obj = {
              id: item.id,
              name: item.name,
              leaf: node.level >= 2,
            };
            nodes.push(obj);
          });
          resolve(nodes);
        }
      });
    }
  },
};
let propsSearch = {
  value: "id",
  label: "name",
  lazy: true,
  checkStrictly: true,
  lazyLoad(node, resolve) {
    const { level } = node;
    let nodes = [];
    let data = {
      upid: node.value,
    };
    if (node.value * 1 >= 32 && node.value * 1 <= 36) {
      request({
        url: "/common/district/search",
        data,
      }).then((res) => {
        if (res.code == "1") {
          res.data.page_data.map((item) => {
            let obj = {
              id: item.id,
              name: item.name,
              leaf: node.level >= 1,
            };
            nodes.push(obj);
          });
          resolve(nodes);
        }
      });
    } else {
      request({
        url: "/common/district/search",
        data,
      }).then((res) => {
        if (res.code == "1") {
          res.data.page_data.map((item) => {
            let obj = {
              id: item.id,
              name: item.name,
              leaf: node.level >= 2,
            };
            nodes.push(obj);
          });
          resolve(nodes);
        }
      });
    }
  },
}
// 编辑弹窗
let id = $ref("");
function editData(val) {
  dialogVisible = true;
  id = val.id;
  tiny_id = 'xxfc'+val.id;
  title = "编辑";
  isEdit = true;
  request({
    url: "/school/main/detail",
    data: {
      id: val.id,
    },
  }).then((res) => {
    if (res.code == "1") {
      Object.keys(ruleForm).forEach((key, item) => {
        ruleForm[key] = res.data.one_info[key];
      });
      if (res.data.one_info.sm_area_id1 * 1 >= 32 && res.data.one_info.sm_area_id1 * 1 <= 36) {
        ruleForm.sm_address = [
          res.data.one_info.sm_area_id1,
          res.data.one_info.sm_area_id2
        ];
      } else {
        ruleForm.sm_address = [
          res.data.one_info.sm_area_id1,
          res.data.one_info.sm_area_id2,
          res.data.one_info?.sm_area_id3 == 0 ? '' : res.data.one_info?.sm_area_id3,
        ];
      }
      ruleForm.detail_area = res.data.one_info.sm_address;
      ruleForm.sm_brief = res.data.one_info.sm_brief;
      handleChange(ruleForm.sm_address)

    }
  });
}

// 详情弹窗
let detailInfo = $ref({});
let detailVisible = $ref(false);
function detailData(item) {
  detailVisible = true;
  request({
    url: "/school/main/detail",
    data: {
      id: item.id,
    },
  }).then((res) => {
    if (res.code == "1") {
      detailInfo = res.data.one_info;
    }
  });
}

let isButton = $ref(false);
// 新增/编辑提交
function submitForm(formName) {
  if (!formName) return;
  formName.validate((valid) => {
    if (valid) {
      let data = {
        school_main: {
          ..._.omit(ruleForm, "sm_address", "detail_area", 'sm_address_detail'),
          sm_address: ruleForm.detail_area,
          sm_area_id1: ruleForm.sm_address[0],
          sm_area_id1_name: address_name[0],
          sm_area_id2: ruleForm.sm_address[1],
          sm_area_id2_name: address_name[1],
          sm_area_id3: ruleForm?.sm_address[2],
          sm_area_id3_name: address_name[2],
        },
      };
      console.log(data);
      isButton = true;
      if (!isEdit) {
        request({
          url: "/school/main/add",
          data,
        }).then((res) => {
          if (res.code == "1") {
            ElMessage({
              type: "success",
              message: res.msg,
            });
            dialogVisible = false;
            initData();
            isButton = false;
          }
        });
      } else {
        Object.assign(data, {
          id: id,
        });
        console.log(data);
        isButton = true;
        request({
          url: "/school/main/edit",
          data,
        }).then((res) => {
          ElMessage({
            type: "success",
            message: res.msg,
          });
          dialogVisible = false;
          initData();
          isButton = false;
        });
      }
    } else {
      isButton = false;
    }
  });
}
// 批量删除
function deleteMul() {
  ElMessageBox.confirm("确认删除这些数据?", "", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      request({
        url: "/school/main/delete",
        data: {
          id: multipleSelection,
        },
      }).then((res) => {
        if (res.code == "1") {
          ElMessage({
            type: "success",
            message: "删除成功",
          });
          initData();
        } else {
          ElMessage({
            type: "success",
            message: res.msg,
          });
        }
      });
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: "取消操作",
      });
    });
}
// 单个删除
function deleteItem(item) {
  ElMessageBox.confirm("确认删除?", "", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning",
  }).then(() => {
      request({
        url: "/school/main/delete",
        data: {
          id: item.id,
        },
      }).then((res) => {
        if (res.code == "1") {
          ElMessage({
            type: "success",
            message: "删除成功",
          });
          initData();
        } else {
          ElMessage({
            type: "success",
            message: res.msg,
          });
        }
      });
    }).catch(() => {
      ElMessage({
        type: "info",
        message: "取消操作",
      });
    });
}

// 导出
function exportData() {
  let data = {
    id: multipleSelection,
  };
  download("school/main/index", data);
}

function ktyjLink(item) {
  router.push({
    path: "/msgzs/ktyj",
    query: {
      id: item.id,
    },
  });
}
</script>
<style lang="scss" scoped>
@use "~/styles/table.scss";
@use "~/styles/pagination.scss";

.el-input,
.el-select {
  width: 200px;
}

.tableList {
  height: calc(100% - 32px);

  .tableDiv {
    height: calc(100% - 32px - 50px);
  }
}

.center {
  text-align: center;
}

.search {
  height: 72px;
  line-height: 85px;
  padding: 0 29px;
}

.el-input.rank {
  min-width: 200px;
}

.total {
  span {
    width: 80px;
  }
}

.member {
  margin: 5px 0;

  .el-input {
    width: 200px;
  }
}

.detail_dialog {
  width: 420px;
  margin: 0 auto;

  >div {
    width: 100%;
    margin: 15px 0;
    color: #000;
  }

  .span_label {
    text-align: right;
    display: inline-block;
    width: 90px;
  }
}
</style>