<template>
  <div class="bg-white rounded-md h-screen py-4">
    <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
          :id="'xxcf'"
          class="w-520px"
          v-model="ruleForm.sm_brief"
        ></TinymceVue>
      </el-form-item>
    </el-form>
    <div class="text-center">
      <el-button
        type="primary"
        :disabled="isButton"
        @click="submitForm(ruleFormRef)"
      >
        确定 </el-button
      ><el-button @click="cancelForm">取消</el-button>
    </div>
  </div>
</template>
<script setup>
import { useRouter } from "vue-router";
import { user } from '@/store/index'
import _ from "lodash";
console.log(user.value.sm_id,'user');
const router = useRouter();
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: '',
});
request({
  url:'/school/main/detail',
  data:{
    id: user.value.sm_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)
  }
})

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 xdList = $ref([]);
request({
  url: "/common/sjzd/option",
  data: {
    cs_code: "XD",
  },
}).then((res) => {
  if (res.code == "1") {
    xdList = res.data.option;
  }
});

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 = [];

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 isButton = $ref(false);
// 提交
function submitForm(formName) {
  if (!formName) return;
  formName.validate((valid) => {
    let data = {
      id: user.value.sm_id,
      // id: '10001',
      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],
      },
    };
    if (valid) {
        isButton = true;
        request({
          url: "/school/main/edit",
          data,
        }).then((res) => {
          if (res.code == "1") {
            ElMessage({
              type: "success",
              message: res.msg,
            });
            router.push({ name: "xj_detail" })
            isButton = false;
          }
        });
    } else {
      isButton = false;
    }
  });
}
function cancelForm() {
  router.go(-1);
}
</script>
<style lang="scss" scoped>
.el-input,
.el-select {
  width: 200px;
}
.el-input.rank {
  min-width: 200px;
}
.demo-ruleForm {
  width: 800px;
  height: calc(80% - 50px);
  margin: 0 auto;
  overflow: auto;
}
</style>