<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-select
            clearable
            @clear="initData"
            v-model="tm_xd"
            placeholder="全部学段"
            class="w-40"
          >
            <el-option
              v-for="g in xdList"
              :key="g.v"
              :label="g.n"
              :value="g.v"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-select
            clearable
            @clear="initData"
            v-model="tjzx_id"
            placeholder="全部学科"
            class="w-40"
          >
            <el-option
              v-for="s in xkList"
              :key="s.tjzx_id"
              :label="s.tjzx_xkmc"
              :value="s.tjzx_id"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <div>
        <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">
        <div>
          <el-button type="primary" @click="addData">新增</el-button>
          <el-button type="primary" @click="exportData">导出</el-button>
          <import-button url="/txwx/msgzs" @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 rank"
            size="small"
            clearable
            @clear="initData"
            placeholder="请输搜索关键词"
            :suffix-icon="Search"
          />
          <el-button type="primary" @click="initData">查询</el-button>
        </div>
      </div>
      <el-divider />
      <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="tm_id"
              label="信息编号"
              width="100"
            ></el-table-column>
            <el-table-column
              prop="tm_gzsmc"
              label="工作室名称"
              width="120"
              show-overflow-tooltip=""
            ></el-table-column>
            <el-table-column
              prop="tm_xd_option_n"
              label="学段"
              width="80"
            ></el-table-column>
            <el-table-column
              prop="tjzx_name"
              label="学科"
              width="80"
            ></el-table-column>
            <el-table-column prop="tm_cys" label="成员数"></el-table-column>
            <el-table-column prop="tm_zys" label="资源数"></el-table-column>
            <el-table-column prop="tm_fws" label="访问数"></el-table-column>
            <el-table-column prop="tm_pm" label="排名"></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
                ><el-divider direction="vertical" />
                <el-button type="text" @click="ktyjLink(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="[10, 20, 50, 100]"
            :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="工作室名称" prop="tm_gzsmc">
          <el-input v-model="ruleForm.tm_gzsmc" />
        </el-form-item>
        <el-form-item label="封面" prop="tm_img">
          <file-upload-progress
            v-model:part="ruleForm.tm_img"
            :limit="1"
            class="w-500px"
            accept=".jpg,.jpeg,.webp,.png"
            :size-limit="500 * 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文件，且不超过500kb，建议尺寸600x337
              </div>
            </template>
          </file-upload-progress>
        </el-form-item>
        <el-form-item label="封面地址">
          <el-input v-model="ruleForm.tm_img" />
        </el-form-item>
        <div class="flex">
          <el-form-item label="学科" prop="tjzx_id">
            <el-select v-model="ruleForm.tjzx_id">
              <el-option
                v-for="s in xkList"
                :key="s.tjzx_id"
                :label="s.tjzx_xkmc"
                :value="s.tjzx_id"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="学段" prop="tm_xd">
            <el-select v-model="ruleForm.tm_xd">
              <el-option
                v-for="g in xdList"
                :key="g.v"
                :label="g.n"
                :value="g.v"
              ></el-option>
            </el-select>
          </el-form-item>
        </div>
        <div class="total mb-5">
          <el-form-item v-for="(p, i) in memberData" :key="i" label-width="0">
            <div class="flex justify-between">
              <div class="w-80px text-center">
                <div class="text-blue-500" v-if="i == 0">成员信息</div>
                <div class="text-blue-500" v-if="i > 0">
                  成员信息{{ i + 1 }}
                </div>
              </div>
              <div>
                <div class="h-40px w-full justify-end flex items-center">
                  <el-icon
                    v-show="i > 0"
                    @click="deleteMember(i)"
                    color="#409eff"
                    size="20px"
                    ><Delete
                  /></el-icon>
                </div> 
                <div class="flex w-full member items-center">
                  <span>姓名:</span> <remote-user-select
                    class="w-200px h-40px py-5px"
                    size="small"
                    v-model="p.tmc_cyzh"
                    v-model:model-real-name="p.tmc_cyxm"
                    :d="{ user_role_id: '75' }"
                  ></remote-user-select>
                  <span class="ml-5">账号:</span>
                  <el-input size="small" v-model="p.tmc_cyzh" />
                </div>
                <div class="flex member items-center">
                  <span>身份证号:</span> <el-input v-model="p.tmc_sfzh" />
                </div>
                <div class="flex">
                  <span> 简介:</span>
                  <tinymceVue
                    v-if="dialogVisible"
                    :id="'index' + i"
                    class="w-500px "
                    v-model="p.tmc_cyjj"
                  ></tinymceVue>
                </div>
              </div>
            </div>
          </el-form-item>
          <el-button class="ml-100px" @click="addMember" type="primary" plain
            >添加</el-button
          >
        </div>
        <el-form-item label="排名" prop="tm_pm">
          <el-input class="rank" v-model="ruleForm.tm_pm" />
        </el-form-item>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button
            type="primary"
            :disabled="isButton"
            @click="submitForm(ruleFormRef)"
          >
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>
    <el-dialog v-model="detailVisible" title="详情" width="680px">
      <div class="detail_dialog">
        <div class="">
          <span class="span_label">工作室名称：</span>
          {{ detailInfo.tm_gzsmc }}
        </div>
        <div class="flex">
          <span class="span_label">封面：</span
          ><img v-if="detailInfo.tm_img" class="w-200px" :src="getFullUrl(detailInfo.tm_img) " alt="" />
        </div>
        <div>
          <span class="span_label">封面地址：</span>{{ getFullUrl(detailInfo.tm_img) }}
        </div>
        <div class="flex justify-between">
          <div>
            <span class="span_label">学段：</span
            >{{ detailInfo.tm_xd_option_n }}
          </div>
          <div>
            <span class="span_label">学科：</span>{{ detailInfo.tjzx_name }}
          </div>
        </div>
        <div>
          <div
            class="mb-6 detail_dialog"
            v-for="(m, i) in detailMember"
            :key="m.id"
          >
            <p class="text-blue-500 mb-3">成员信息{{ i + 1 }}</p>
            <div class="flex justify-between ml-2">
              <div><span class="span_label">姓名：</span>{{ m.tmc_cyxm }}</div>
              <div><span class="span_label">账号：</span>{{ m.tmc_cyzh }}</div>
            </div>
            <div>
              <span class="span_label">身份证号：</span>{{ m.tmc_sfzh }}
            </div>
            <div class="flex">
              <span class="span_label">简介：</span>
              <div v-html="m.tmc_cyjj"></div>
            </div>
          </div>
        </div>
        <div><span class="span_label">排名：</span>{{ detailInfo.tm_pm }}</div>
      </div>
      <div class="center my-15">
        <el-button type="primary" @click="detailVisible = false"
          >返回</el-button
        >
      </div>
    </el-dialog>
    <el-dialog
      v-model="importVisible"
      title="批量导入"
      width="520px"
      class="min-h-280px"
    >
      <div class="px-15">
        <div class="absolute right-20">
          <span
            class="text-blue-500 font-medium cursor-pointer"
            @click="exportOne"
            >下载模板</span
          >
        </div>
        <file-upload-progress :limit="1" v-model:full="importfile" class="w-full"></file-upload-progress>
      </div>
      <div class="center mt-25">
        <el-button type="primary" @click="importData">确定</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 { useRouter } from "vue-router";
import request from "@/utils/request";
const router = useRouter();
let tm_xd = $ref("");
let xdList = $ref([]);
let tjzx_id = $ref("");
let xkList = $ref([]);
let keyword = $ref("");
let tableData = $ref([]);
let multipleSelection = $ref([]);
let importVisible = $ref(false);
let nowTime = Date.now();
request({
  url: "/common/sjzd/option",
  data: {
    cs_code: "XD",
  },
}).then((res) => {
  xdList = res.data.option;
});
request({
  url: "/txwx/jcxxgl_zyflgl_xk/index",
  data: {
    limit: "9999",
    page: "1",
  },
}).then((res) => {
  xkList = res.data.page_data;
});

const handleSelectionChange = (val) => {
  multipleSelection = [];
  val.forEach((i) => {
    multipleSelection.push(i.tm_id);
  });
};
function handleSizeChange(val) {
  form_query.limit = val;
  form_query.page = 1;
  initData();
}
function handleCurrentChange(val) {
  form_query.page = val;
  initData();
}
let total = $ref(10);
const form_query = $ref({
  page: 1,
  limit: 6,
});
initData();
function initData() {
  let data = {
    ...form_query,
    keyword,
    tm_xd,
    tjzx_id,
  };
  request({
    url: "/txwx/msgzs/index",
    data,
  }).then((res) => {
    if (res.code == "1") {
      tableData = res.data.page_data;
      total = Number(res.data.total_rows);
    }
  });
}
const ruleFormRef = $ref();
let ruleForm = $ref({
  tm_gzsmc: "",
  tm_img: "",
  tm_pm: "",
  tjzx_id: "",
  tjzx_name:'',
  tm_xd: "",
});
let memberData = $ref([
  {
    tmc_cyxm: "",
    tmc_cyzh: "",
    tmc_sfzh: "",
    tmc_cyjj: "",
  },
]);
const rules = $ref({
  tm_gzsmc: [
    {
      required: true,
      message: "请填写工作室名称",
      trigger: "submit",
    },
  ],
  tm_img: [{ required: true, message: "请上传封面", trigger: "submit" }],
  tm_xd: [{ required: true, message: "请选择学段", trigger: "submit" }],
  tjzx_id: [{ required: true, message: "请选择学科", trigger: "submit" }],
  tm_pm: [{ required: true, message: "请输入排名", trigger: "submit" }],
});
let dialogVisible = $ref(false);
let title = $ref("");
let isEdit = $ref(false);
// 新增弹窗
function addData() {
  dialogVisible = true;
  title = "新增";
  isEdit = false;
  nowTime = Date.now()
  Object.keys(ruleForm).find((item) => {
    ruleForm[item] = "";
  });
  ruleForm.tm_img = '';
  ruleForm[tjzx_id] = {};
  memberData = [
    {
      tmc_cyxm: "",
      tmc_cyzh: "",
      tmc_sfzh: "",
      tmc_cyjj: "",
    },
  ];
}
// 添加成员
function addMember() {
  memberData.push({
    tmc_cyxm: "",
    tmc_cyzh: "",
    tmc_sfzh: "",
    tmc_cyjj: "",
  });
}
// 删除成员
function deleteMember(index) {
  memberData.splice(index, 1);
}
// 编辑弹窗
let tm_id;
function editData(val) {
  dialogVisible = true;
  tm_id = val.tm_id;
  title = "编辑";
  isEdit = true;
  Object.keys(ruleForm).find((item) => {
    ruleForm[item] = val[item];
  });
  ruleForm.tm_xd = val.tm_xd_option_k
  let tm_cy = val.tm_cy;
  memberData = JSON.parse(tm_cy);
  nowTime = Date.now()
  console.log(ruleForm,22222);
}
// 详情弹窗
let https = window.GLOBAL_CONFIG.api;
let detailInfo = $ref({});
let detailMember = $ref([]);
let detailVisible = $ref(false);
function detailData(item) {
  detailVisible = true;
  request({
    url: "/txwx/msgzs/detail",
    data: {
      tm_id: item.tm_id,
    },
  }).then((res) => {
    if (res.code == "1") {
      detailInfo = res.data.one_info;
      let m = res.data.one_info.tm_cy;
      detailMember = JSON.parse(m);
    }
  });
}

// 获取用户列表
let userList = $ref([]); 
function getUserList() {
    request({
    url: '/user/main/index',
    data: {
      page: '1',
      limit: 100,
      user_role_id: '75',
    }
  }).then(res => {
    if (res.code == '1') {
      userList = res.data.page_data
    }
  })
}
getUserList();


let isButton = $ref(false);
// 新增/编辑提交
function submitForm(formName) {
  if (!formName) return;
  formName.validate((valid) => {
    if (valid) {
      memberData.forEach(item => {
        userList.forEach(key => {
          if (key.user_id === item.tmc_cyzh) {
            item.user_score = key.user_score;
            item.user_dept = key.user_dept? key.user_dept : key.ext?.ue_xxmc;
          }
        })
      })
      xkList.forEach(item => {
        if (item.tjzx_id == ruleForm.tjzx_id) {
          ruleForm.tjzx_name = item.tjzx_xkmc
        }
      })
      console.log(memberData,'mmmmm');
      let flag = false;
      let a = [];
      memberData.forEach((item) => {
        let b = {};
        if (
          !item.tmc_cyjj ||
          !item.tmc_cyxm ||
          !item.tmc_cyzh ||
          !item.tmc_sfzh
        ) {
          flag = true;
        } else {
          b = {
            tmc_cyjj: item.tmc_cyjj,
            tmc_cyxm: item.tmc_cyxm,
            tmc_cyzh: item.tmc_cyzh,
            tmc_sfzh: item.tmc_sfzh,
            user_score: item.user_score,
            user_dept: item.user_dept,
          };
        }
        a.push(b);
      });
      if (flag) {
        return ElMessage({
          type: "warning",
          message: "请填写完整成员信息",
        });
      }
      let data = {
        txwx_msgzs: {
          tm_gzsmc: ruleForm.tm_gzsmc,
          tm_img: ruleForm.tm_img,
          tm_pm: ruleForm.tm_pm,
          tjzx_id: ruleForm.tjzx_id,
          tjzx_name: ruleForm.tjzx_name,
          tm_xd: ruleForm.tm_xd,
          tm_cys: a.length,
          tm_cy: JSON.stringify(a),
        },
      };
      console.log(data);
      if (!isEdit) {
        isButton = true;
        request({
          url: "/txwx/msgzs/add",
          data,
        }).then((res) => {
          if (res.code == "1") {
            ElMessage({
              type: "success",
              message: res.msg,
            });
            dialogVisible = false;
            initData();
            isButton = false;
          }
        });
      } else {
        Object.assign(data, {
          tm_id,
        });
        request({
          url: "/txwx/msgzs/edit",
          data,
        }).then((res) => {
          if (res.code == "1") {
            ElMessage({
              type: "success",
              message: res.msg,
            });
            dialogVisible = false;
            initData();
            isButton = false;
          }
        });
      }
    } else {
      isButton = false;
    }
  });
}

// 导出
function exportData(){
  let data = {
    tm_id: multipleSelection,
    limit:9999,
    page:1
  }
  download('txwx/msgzs/index',data)
}
// 下载模板
function exportOne(){
  let data = {
    limit:1,
    page:1
  }
  download('txwx/msgzs/index',data)
}
// 批量导入
let importfile = $ref('');
function importData() {
  console.log(importfile);
  if (!importfile) {
    return ElMessage({
      type: "warning",
      message: "请上传文件",
    });
  }
  request({
    $type: 'import',
    url:'txwx/msgzs/import',
    data:{ file: importfile }
  });
}

// 批量删除
function deleteMul() {
  ElMessageBox.confirm("确认删除这些数据?", "", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      request({
        url: "/txwx/msgzs/delete",
        data: {
          tm_id: multipleSelection.join(","),
        },
      }).then((res) => {
        if (res.code == "1") {
          ElMessage({
            type: "success",
            message: res.msg,
          });
          initData();
        } else {
          ElMessage({
            type: "info",
            message: res.msg,
          });
        }
      });
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: "取消操作",
      });
    });
}
// 单个删除
function deleteItem(item) {
  ElMessageBox.confirm("确认删除?", "", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      request({
        url: "/txwx/msgzs/delete",
        data: {
          tm_id: item.tm_id,
        },
      }).then((res) => {
        if (res.code == "1") {
          ElMessage({
            type: "success",
            message: res.msg,
          });
          initData();
        } else {
          ElMessage({
            type: "info",
            message: res.msg,
          });
        }
      });
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: "取消操作",
      });
    });
}
function ktyjLink(item) {
  router.push({
    path: "/manage/msgzs/ktyj",
    query: {
      id: item.tm_id,
    },
  });
}
</script>
<style lang="scss" scoped>
@use "~/styles/table.scss";
@use "~/styles/pagination.scss";
.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 {
  width: 200px;
}
.total {
  span {
    width: 80px;
  }
}
.member {
  margin: 5px 0;
  .el-input {
    width: 200px;
    height: 30px;
  }
}
.el-input {
  width: 500px;
}
.detail_dialog {
  width: 520px;
  margin: 0 auto;
  > div {
    width: 100%;
    margin: 15px 0;
    color: #000;
  }
  .span_label {
    text-align: right;
    display: inline-block;
    width: 90px;
  }
}
</style>