<template>
  <div class="m-container" v-cloak>
    <h2>
      <div class="squrt"></div>
      合作单位
    </h2>
    <transition name="el-fade-in-linear">
      <div
        class="m-core"
        v-if="((tableList.length > 0 || pageInfo.page > 1) && contextFlag) || !isSearch"
      >
        <!-- 搜索类型 -->
        <save-form
          :inline="true"
          class="searchForm"
          ref="searchForm"
          @submit="search"
          @reset="onReSet"
          :model="searchForm"
        >
          <el-form-item prop="search">
            <el-input
              v-model="searchForm.search"
              clearable
              placeholder="单位/乐团主管名称"
            ></el-input>
          </el-form-item>
          <el-form-item prop="organId">
            <el-select
              v-model.trim="searchForm.organId"
              placeholder="请选择分部"
              filterable
              clearable
            >
              <el-option
                v-for="item in selects.branchs"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item prop="isEnable">
            <el-select
              v-model.trim="searchForm.isEnable"
              placeholder="请选择状态"
              filterable
              clearable
            >
              <el-option label="开启" :value="true"></el-option>
              <el-option label="关闭" :value="false"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button native-type="submit" type="danger">搜索</el-button>
            <el-button native-type="reset" type="primary">重置</el-button>
            <!-- export/isSettlementCourseSalarys  -->
            <el-button
              @click="onExport"
              v-permission="'export/cooperationOrgan'"
              type="primary"
              >导出</el-button
            >
          </el-form-item>
        </save-form>
        <el-button
          @click="openTeaching('create')"
          v-permission="'cooperationOrgan/add'"
          type="primary"
          style="margin-bottom: 20px"
        >
          新建
        </el-button>

        <!-- 列表 -->
        <div class="tableWrap">
          <el-table
            :data="tableList"
            :header-cell-style="{ background: '#EDEEF0', color: '#444' }"
          >
            <el-table-column align="center" prop="id" label="单位编号"> </el-table-column>
            <el-table-column align="center" prop="name" label="单位名称">
            </el-table-column>
            <el-table-column align="center" prop="logo" label="logo">
              <template slot-scope="scope">
                <el-image
                  style="width: 100px; height: 100px"
                  :src="scope.row.logo"
                  :preview-src-list="[scope.row.logo]"
                >
                </el-image>
              </template>
            </el-table-column>
            <el-table-column align="center" prop="name" label="所属分部">
              <template slot-scope="scope">
                <div>
                  {{ scope.row.organization.name }}
                </div>
              </template>
            </el-table-column>
            <el-table-column align="center" prop="realName" label="乐团主管">
            </el-table-column>
            <!-- <el-table-column align="center" prop="linkman" label="联系人">
          </el-table-column>
          <el-table-column align="center" prop="job" label="职位">
          </el-table-column>
          <el-table-column align="center" prop="mobileNo" label="手机号">
          </el-table-column> -->
            <el-table-column align="center" label="是否全职资源" v-if="tenantId == 1">
              <template slot-scope="scope">
                {{ scope.row.fullJobResource ? "是" : "否" }}
              </template>
            </el-table-column>
            <el-table-column align="center" label="状态">
              <template slot-scope="scope">
                <div>
                  {{ scope.row.isEnable ? "开启" : "关闭" }}
                </div>
              </template>
            </el-table-column>

            <el-table-column align="center" label="操作" width="140px">
              <template slot-scope="scope">
                <el-button @click="openTeaching('look', scope.row)" type="text"
                  >查看</el-button
                >
                <el-button
                  @click="openTeaching('update', scope.row)"
                  v-permission="'cooperationOrgan/update'"
                  type="text"
                  >修改</el-button
                >
                <el-button
                  @click="onDelete(scope.row)"
                  v-permission="'cooperationOrgan/del'"
                  type="text"
                  >删除</el-button
                >
                <el-button @click="rejuest(scope.row)" type="text">领队注册</el-button>
              </template>
            </el-table-column>
          </el-table>
          <pagination
            sync
            :total.sync="pageInfo.total"
            :page.sync="pageInfo.page"
            :limit.sync="pageInfo.limit"
            :page-sizes="pageInfo.page_size"
            @pagination="getList"
          />
        </div>
      </div>

      <emptyPage
        @submit="openTeaching('create')"
        title="合作单位"
        btnTitle="新建合作单位"
        :context="context"
        v-if="!(tableList.length > 0 || pageInfo.page > 1) && contextFlag && isSearch"
      />
    </transition>
    <el-dialog
      :title="formTitle[formActionTitle]"
      :visible.sync="teachingStatus"
      width="1060px"
      v-if="teachingStatus"
    >
      <el-form
        :model="form"
        :rules="rules"
        ref="ruleForm"
        :inline="true"
        class="eidtForm"
        label-position="left"
      >
        <el-alert
          style="margin: 10px 0"
          title="合作单位信息"
          :closable="false"
          type="info"
        >
        </el-alert>
        <el-row>
          <el-form-item label="单位名称" prop="name" :label-width="formLabelWidth">
            <el-input
              v-model.trim="form.name"
              :disabled="basdisabled"
              autocomplete="off"
            ></el-input>
          </el-form-item>
          <el-form-item label="所属分部" prop="organId" :label-width="formLabelWidth">
            <el-select
              :disabled="basdisabled"
              v-model.trim="form.organId"
              @change="changeOrgan"
              filterable
              clearable
            >
              <el-option
                v-for="item in selects.branchs"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-row>
        <el-row>
          <el-form-item
            label="乐团主管"
            prop="educationUserId"
            :label-width="formLabelWidth"
            :rules="[{ required: true, message: '乐团主管不能为空' }]"
          >
            <el-select
              :disabled="!form.organId || basdisabled"
              v-model.trim="form.educationUserId"
              filterable
              clearable
            >
              <el-option
                v-for="(item, key) in educationList"
                :key="key"
                :label="item.userName"
                :value="item.userId"
              >
                <span style="float: left">{{ item.userName }}</span>
                <span style="float: right; color: #8492a6; font-size: 13px">{{
                  String(item.userId)
                }}</span>
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item
            label="合作单位状态"
            prop="isEnable"
            :label-width="formLabelWidth"
          >
            <el-select
              :disabled="basdisabled"
              v-model.trim="form.isEnable"
              filterable
              clearable
            >
              <el-option label="开启" :value="true"></el-option>
              <el-option label="关闭" :value="false"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item
            v-if="tenantId == 1"
            label="是否全职资源"
            prop="fullJobResource"
            :label-width="formLabelWidth"
          >
            <el-select :disabled="basdisabled" v-model.trim="form.fullJobResource">
              <el-option label="是" :value="1"></el-option>
              <el-option label="否" :value="0"></el-option>
            </el-select>
          </el-form-item>
        </el-row>
        <el-row>
          <el-form-item label="合作单位logo" :label-width="formLabelWidth">
            <image-cropper
              :options="cropperOptions"
              bucket_name="daya"
              :imgSize="2"
              :imageUrl="form.logo"
              showSize
              @crop-upload-success="cropSuccess"
            />
            <p style="color: red">大小2M以内，格式为jpg、png、gif图片</p>
          </el-form-item>
        </el-row>
        <el-alert
          style="margin: 10px 0"
          title="合作单位联系人"
          :closable="false"
          type="info"
        >
        </el-alert>
        <el-row
          v-for="(item, index) in form.cooperationOrganLinkmanList"
          :key="index"
          class="greyRow"
        >
          <div class="concatTitle">
            <p>联系人{{ index + 1 }}</p>
            <i
              class="el-icon-delete-solid marginLeft10 iconStyle"
              v-if="form.cooperationOrganLinkmanList.length > 1 && !basdisabled"
              @click="deleteLinkMan(index)"
              style="font-size: 20px; cursor: pointer"
            ></i>
          </div>
          <el-form-item
            :rules="[{ required: true, message: '请输入联系人', trigger: 'blur' }]"
            :label="'联系人姓名'"
            :prop="'cooperationOrganLinkmanList.' + index + '.linkman'"
            :label-width="formLabelWidth"
          >
            <el-input
              :disabled="basdisabled"
              v-model.trim="item.linkman"
              autocomplete="off"
            ></el-input>
          </el-form-item>
          <el-form-item
            :rules="[{ required: true, message: '请输入职位', trigger: 'blur' }]"
            :label="'联系人职位'"
            :prop="'cooperationOrganLinkmanList.' + index + '.job'"
            :label-width="formLabelWidth"
          >
            <el-input
              :disabled="basdisabled"
              v-model.trim="item.job"
              autocomplete="off"
            ></el-input>
          </el-form-item>
          <el-form-item
            :rules="[
              { required: true, validator: validPhone, trigger: 'blur' },
              ,
              {
                pattern: /^1[3456789]\d{9}$/,
                message: '请输入正确的手机号',
                trigger: 'blur',
              },
            ]"
            :label="'联系人手机号'"
            :prop="'cooperationOrganLinkmanList.' + index + '.mobileNo'"
            :label-width="formLabelWidth"
          >
            <el-input
              :disabled="basdisabled"
              :max="11"
              :min="11"
              maxlength="11"
              v-model.trim="item.mobileNo"
              autocomplete="off"
            ></el-input>
          </el-form-item>

          <!-- <i
            class="el-icon-circle-plus-outline marginLeft10 iconStyle"


            style="font-size: 20px; cursor: pointer"
          ></i> -->
        </el-row>
        <!-- index + 1 == form.cooperationOrganLinkmanList.length -->
        <el-button
          v-if="!basdisabled"
          class="greyRow"
          style="width: 100%"
          icon="el-icon-plus"
          @click="addLinkMan"
          >添加联系人</el-button
        >
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="teachingStatus = false">取 消</el-button>
        <el-button
          type="primary"
          v-if="!basdisabled"
          @click="onTeachingSubmit('ruleForm')"
          >确 定</el-button
        >
      </span>
    </el-dialog>
    <qr-code
      v-model="codeStatus"
      title="领队注册"
      :codeUrl="codeUrl"
      :value="radio"
      :isDown="true"
      ref="qrCode"
    >
      <el-radio-group v-model="radio" @change="changeRadio" class="groupWrap">
        <el-radio label="SCHOOL_LEADER">分管领导</el-radio>
        <el-radio label="TEACHER">负责老师</el-radio>
        <el-radio :disabled="staffStat.orchestraLeaderNums > 0" label="ORCHESTRA_LEADER"
          >乐团领队</el-radio
        >

        <el-radio :disabled="staffStat.schoolmasterNums > 0" label="SCHOOLMASTER"
          >学校校长</el-radio
        >
      </el-radio-group>
    </qr-code>
  </div>
</template>
<script>
import pagination from "@/components/Pagination/index";
import {
  cooperationOrganAdd,
  cooperationOrganUpdate,
  cooperationOrganDel,
  queryPage,
} from "@/api/systemManage";
import cleanDeep from "clean-deep";
import { isvalidPhone } from "@/utils/validate";
import { Export } from "@/utils/downLoadFile";
import { getOrganRole } from "@/api/buildTeam";
import emptyPage from "@/components/emptyPage";
import qs from "qs";
import { isBoolean } from "@rongcloud/engine";
import ImageCropper from "@/components/ImageCropper";
import qrCode from "@/components/QrCode/index";
import { vaildTeachingUrl } from "@/utils/validate";
import { getCooperation } from "./api";
let validPhone = (rule, value, callback) => {
  if (!value) {
    callback(new Error("请输入电话号码"));
  } else if (!isvalidPhone(value)) {
    callback(new Error("请输入正确的11位手机号码"));
  } else {
    callback();
  }
};
export default {
  name: "branchManager",
  components: { pagination, emptyPage, ImageCropper, qrCode },
  data() {
    return {
      searchForm: {
        organId: null,
        isEnable: null,
        search: null,
      },
      validPhone,
      searchLsit: [],
      tableList: [],
      educationList: [],
      pageInfo: {
        // 分页规则
        limit: 10, // 限制显示条数
        page: 1, // 当前页
        total: 0, // 总条数
        page_size: [10, 20, 40, 50], // 选择限制显示条数
      },
      teachingStatus: false, // 添加教学点
      formActionTitle: "create",
      formTitle: {
        create: "添加合作单位",
        update: "修改合作单位",
        look: "查看合作单位",
      },
      formLabelWidth: "120px",
      form: {
        id: null,
        name: null, // 教学点名称
        linkman: null, // 来源
        job: null, // 费用
        mobileNo: null,
        fullJobResource: null,
        organId: null,
        educationUserId: null,
        logo: null,
        cooperationOrganLinkmanList: [
          { cooperationOrganId: "", job: "", linkman: "", mobileNo: "" },
        ],
      },
      rules: {
        name: [{ required: true, message: "请输入教学点名称", trigger: "blur" }],

        organId: [{ required: true, message: "请选择所属分部", trigger: "change" }],
        educationUserId: [
          { required: true, message: "请选择乐团主管", trigger: "change" },
        ],
        fullJobResource: [
          { required: true, message: "请选择是否全职资源", trigger: "change" },
        ],
        isEnable: [{ required: true, message: "请选择状态", trigger: "change" }],
      },
      basdisabled: false,
      actionRow: null,
      tenantId: null,
      context:
        "合作单位即为合作学校，可以为本机构下的各个分部创建合作单位，创建乐团时需选择合作单位用于区分和管理各合作方的乐团。若本机构乐团无合作方，可将本机构创建为合作单位，并在创建乐团时选择。",
      contextFlag: false,
      cropperOptions: {
        autoCrop: true, //是否默认生成截图框
        autoCropWidth: 200, //默认生成截图框宽度
        autoCropHeight: 200, //默认生成截图框高度
        fixedBox: true, //是否固定截图框大小 不允许改变
        previewsCircle: false, //预览图是否是圆形
        full: true, // 是否输出原图比例的截图
        enlarge: 2,
        title: "logo", //模态框上显示的标题
      },
      codeStatus: false,
      codeUrl: "www.baidu.com",
      radio: "SCHOOL_LEADER",
      staffStat: {
        orchestraLeaderNums: 0,
        orchestraNums: 0,
        schoolLeaderNums: 0,
        schoolmasterNums: 0,
        studentNums: 0,
        teacherNums: 0,
      },
    };
  },
  async mounted() {
    this.tenantId = this.$helpers.tenantId;
    this.getList(); // 获取列表数据

    // 获取当前用户分部
    await this.$store.dispatch("setBranchs");
    if (this.selects.branchs.length <= 0) {
      this.$bus.$emit("showguide", ["organ"]);
    }
  },
  methods: {
    onDelete(rows) {
      this.$confirm("您确定删除合作单位?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          cooperationOrganDel(rows.id).then((res) => {
            if (res.code == 200) {
              this.$message.success("删除成功");
              this.teachingStatus = false;
              this.getList();
            } else {
              this.$message.error(res.msg);
            }
          });
        })
        .catch(() => {});
    },
    search() {
      this.pageInfo.page = 1;
      this.getList();
    },
    onReSet() {
      this.searchForm = {
        organId: null,
        isEnable: null,
        search: null,
      };

      this.$refs.searchForm.resetFields();
      this.$refs.searchForm.save();
      this.search();
      this.$forceUpdate();
    },
    changeRadio() {
      this.$refs.qrCode.resetImage();
      this.codeUrl = `${vaildTeachingUrl()}/school/#/school-register?id=${
        this.activeRow.id
      }&type=${this.radio}`;
    },
    onExport() {
      Export(
        this,
        {
          url: "/api-web/export/cooperationOrgan",
          fileName: "合作单位.xls",
          method: "post",
          params: qs.stringify(cleanDeep(this.searchForm)),
        },
        "您确定导出合作单位?"
      );
    },
    onTeachingSubmit(formName) {
      // 添加数据
      this.$refs[formName].validate((valid) => {
        if (valid) {
          if (this.formActionTitle == "create") {
            if (this.form.id) {
              // 判断有没有Id，如果有则删除
              delete this.form.id;
            }
            cooperationOrganAdd(this.form).then((res) => {
              if (res.code == 200) {
                this.$message.success("创建成功");
                this.teachingStatus = false;
                this.getList();
              } else {
                this.$message.error(res.msg);
              }
            });
          } else if (this.formActionTitle == "update") {
            cooperationOrganUpdate(this.form).then((res) => {
              if (res.code == 200) {
                this.$message.success("修改成功");
                this.teachingStatus = false;
                this.getList();
              } else {
                this.$message.error(res.msg);
              }
            });
          }
        } else {
          return false;
        }
      });
    },
    getList() {
      this.contextFlag = false;
      queryPage({
        rows: this.pageInfo.limit,
        page: this.pageInfo.page,
        ...this.searchForm,
      }).then((res) => {
        if (res.code == 200 && res.data) {
          // this.contextFlag = res.data.rows.length>0?true:false
          this.contextFlag = true;
          this.tableList = res.data.rows;
          this.pageInfo.total = res.data.total;
        }
      });
    },
    openTeaching(type, rows) {
      // 重置数据
      this.teachingStatus = true;
      this.actionRow = { ...rows } || null;

      this.formActionTitle = type;
      // 修改的时候赋值
      if (type == "update") {
        this.changeOrgan(rows.organId);
        this.form = {
          id: rows.id,
          name: rows.name, // 教学点名称
          linkman: rows.linkman, // 来源
          job: rows.job, // 费用
          mobileNo: rows.mobileNo ? rows.mobileNo : null,
          ownershipType: rows.ownershipType,
          organId: rows.organId,
          fullJobResource: rows.fullJobResource,
          isEnable: rows.isEnable,
          educationUserId: rows.educationUserId,
          logo: rows.logo,
        };

        let cooperationOrganLinkmanList =
          rows.cooperationOrganLinkmanList.length > 0
            ? [...rows.cooperationOrganLinkmanList]
            : [
                {
                  cooperationOrganId: rows.id,
                  job: "",
                  linkman: "",
                  mobileNo: "",
                },
              ];
        this.$set(this.form, "cooperationOrganLinkmanList", cooperationOrganLinkmanList);
        this.basdisabled = false;
      } else if (type == "look") {
        this.changeOrgan(rows.organId);
        this.form = {
          id: rows.id,
          name: rows.name, // 教学点名称
          linkman: rows.linkman, // 来源
          job: rows.job, // 费用
          mobileNo: rows.mobileNo ? rows.mobileNo : null,
          ownershipType: rows.ownershipType,
          organId: rows.organId,
          fullJobResource: rows.fullJobResource,
          isEnable: rows.isEnable,
          educationUserId: rows.educationUserId,
          logo: rows.logo,
        };
        let cooperationOrganLinkmanList =
          rows.cooperationOrganLinkmanList.length > 0
            ? [...rows.cooperationOrganLinkmanList]
            : [];
        this.$set(this.form, "cooperationOrganLinkmanList", cooperationOrganLinkmanList);
        this.basdisabled = true;
        // 查看
      } else {
        this.basdisabled = false;
        this.actionRow = null;
      }
    },
    async changeOrgan(val) {
      this.form.educationUserId = null;
      if (val) {
        try {
          const ruselt = await getOrganRole({
            id: val,
          });
          this.educationList = ruselt?.data?.EDUCATION;

          if (!this.educationList || this.educationList?.length <= 0) {
            this.$bus.$emit("showguide", ["teamManager"]);
          }
        } catch (e) {
          console.log(e);
        }
      }
    },
    deleteLinkMan(index) {
      this.form.cooperationOrganLinkmanList.splice(index, 1);
    },
    addLinkMan() {
      if (this.actionRow) {
        // 修改
        this.form.cooperationOrganLinkmanList.push({
          cooperationOrganId: this.actionRow.id,
          job: "",
          linkman: "",
          mobileNo: "",
        });
      } else {
        // 新增
        this.form.cooperationOrganLinkmanList.push({
          cooperationOrganId: "",
          job: "",
          linkman: "",
          mobileNo: "",
        });
      }
    },
    cropClose() {
      console.log("上传操作结束");
    },
    //上传图片成功
    cropSuccess(data) {
      // this.imgUrl = data.data.avatar
      // this.form.logo = data.data.url;
      this.$set(this.form, "logo", data.data.url);
      console.log(this.form.logo, "cropSuccess");
    },
    async rejuest(row) {
      // 查询该单位是否有 校长 乐团领队
      try {
        const res = await getCooperation({ id: row.id });
        console.log(res, "rejuest");
        this.staffStat = { ...res.data.staffStat };
        this.activeRow = row;
        this.codeUrl = `${vaildTeachingUrl()}/school/#/school-register?id=${
          row.id
        }&type=${this.radio}`;
        this.codeStatus = true;
      } catch (e) {}
    },
  },
  watch: {
    teachingStatus(val) {
      if (!val) {
        this.form = {
          id: null,
          name: null, // 教学点名称
          linkman: null, // 来源
          job: null, // 费用
          mobileNo: null,
          fullJobResource: null,
          organId: null,
          isEnable: null,
          educationUserId: null,
          cooperationOrganLinkmanList: [],
        };
        this.$refs.ruleForm.resetFields();
      }
    },
  },
  computed: {
    isSearch() {
      return (
        !this.searchForm.search &&
        !this.searchForm.organId &&
        !isBoolean(this.searchForm.isEnable) &&
        !this.searchForm.isEnable
      );
    },
  },
};
</script>
<style lang="scss" scoped>
// .groupWrap {
//   display: flex;
//   flex-direction: row;
//   justify-content: space-around;
//   flex-wrap: wrap;
// }
.eidtForm {
  ::v-deep .el-form-item__content {
    display: block !important;
  }
  // ::v-deep .el-form--inline {

  // }
  ::v-deep .el-select {
    width: 300px !important;
  }
  ::v-deep .el-date-editor {
    width: 300px !important;
  }
  ::v-deep .el-checkbox {
    margin-left: 15px !important;
  }
  ::v-deep .el-input {
    position: relative;
    font-size: 14px;
    display: inline-block;
    width: 300px !important;
  }
}
.greyRow {
  background-color: #f9f9f9;
  padding: 10px;
  margin-bottom: 10px;
}

::v-deep .el-select {
  width: 100% !important;
}
.el-vue-search-box-container {
  position: absolute !important;
  left: 10px;
  margin-top: 10px;
  z-index: 99999 !important;
}

.iconStyle {
  color: #999;
  line-height: 40px;
}
.marginLeft10 {
  margin-left: 10px;
}
.concatTitle {
  line-height: 36px;
  font-size: 14px;
  font-weight: bold;
  display: flex;
  flex-direction: row;
  justify-content: space-between;
}
</style>
