<template>
  <div>
    <el-form :model="musicForm" label-width="110px" ref="form">
      <el-form-item label="选择学员" prop="studentId" v-if="this.chioseStudent"  :rules="[
          { required: true, message: '请选择学员', trigger: 'blur' },
        ]">
        <el-select
        style="width: 400px !important"
          v-model.trim="musicForm.studentId"
          clearable
          placeholder="请选择"
          remote
          filterable
          :remote-method="remoteMethod"
          :loading="remoteLoading"
        >
          <el-option
            v-for="item in studentList"
            :key="item.userId"
            :label="item.username"
            :value="item.userId"
          >
            <span style="float: left">{{ item.username }}</span>
            <span style="float: right; color: #8492a6; font-size: 13px">{{
              item.parentsPhone
            }}</span>
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item
        label="乐器分类"
        prop="goodsCategoryId"
        :rules="[
          { required: true, message: '请选择乐器分类', trigger: 'blur' },
        ]"
      >
        <el-form-item>
          <el-select
            style="width: 400px !important"
            v-model.trim="musicForm.goodsCategoryId"
            filterable
            clearable
            @change="changeCategory"
            placeholder="乐器分类"
          >
            <el-option
              v-for="(item, index) in typeList"
              :key="index"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-form-item>
      <el-form-item
        label="乐器名称"
        prop="goodsId"
        :rules="[
          { required: true, message: '请选择乐器名称', trigger: 'blur' },
        ]"
      >
        <el-select
          style="width: 400px !important"
          :disabled="!musicForm.goodsCategoryId"
          v-model.trim="musicForm.goodsId"
          filterable
          clearable
          placeholder="乐器名称"
        >
          <el-option
            v-for="(item, index) in musicList"
            :key="index"
            :label="item.name"
            :value="item.id"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item
        label="是否乐保"
        prop="status"
        :rules="[
          { required: true, message: '请选择是否乐保', trigger: 'blur' },
        ]"
      >
        <el-select
          style="width: 400px !important"
          v-model.trim="musicForm.status"
          clearable
          placeholder="是否乐保"
        >
          <el-option value="0" label="否"></el-option>
          <el-option value="1" label="是"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item
        label="乐保结束日期"
        :rules="[
          { required: true, message: '请选择乐保结束日期', trigger: 'blur' },
        ]"
        v-if="musicForm.status == 1"
        prop="date"
      >
        <el-date-picker
          style="width: 400px"
          v-model="musicForm.date"
          clearable
          type="datetime"
          value-format="yyyy-MM-dd HH:mm:ss"
          default-time="23:59:59"
          :picker-options="pickerOptions"
          placeholder="乐保结束日期"
        >
        </el-date-picker>
      </el-form-item>
    </el-form>
  </div>
</template>
<script>
import { goodsQuery } from "@/api/businessManager";
import { addStudentInstrument, updateStudentInstrument } from "@/api/buildTeam";
import { getToken, getTenantId } from "@/utils/auth";
import { getTimes } from "@/utils";
import axios from "axios";
import dayjs from "dayjs";
export default {
  props: ["categoryList", "operationData", "operationStatus", "chioseStudent"],
  data() {
    return {
      musicForm: {
        studentId: this.$route.query.userId,
        goodsId: "",
        goodsCategoryId: "",
        status: "",
        date: null,
      },
      pickerOptions: {
        firstDayOfWeek: 1,
        disabledDate(time) {
          let times = dayjs(dayjs().format("YYYY-MM-DD")).valueOf();
          return times > time.getTime();
        },
      },
      typeList: this.categoryList,
      musicList: [],
      remoteLoading: false,
      studentList: [],
    };
  },
  async mounted() {
    console.log(this.operationData);
    let operationData = this.operationData;
    if (operationData) {
      let musicForm = this.musicForm;
      musicForm.goodsCategoryId = operationData.goodsCategoryId;
      if (operationData.goodsCategoryId) {
        await this.changeCategory(operationData.goodsCategoryId);
      }
      musicForm.studentId = operationData.studentId;
      musicForm.goodsId = operationData.goodsId;
      musicForm.goodsName = operationData.goodsName;
      musicForm.status = operationData.status + "";
      musicForm.date = operationData.endTime || null;
      musicForm.id = operationData.id;
      this.remoteMethod(musicForm.studentId);
    }
  },
  methods: {
    changeCategory(val) {
      this.musicForm.goodsName = "";
      this.musicForm.goodsId = null;
      if (val) {
        goodsQuery({
          goodsCategoryId: val,
          rows: 99999,
          type: "INSTRUMENT",
        }).then((res) => {
          if (res.code == 200 && res.data) {
            this.musicList = res.data.rows;
          }
        });
      }
    },
    addMusicSubmit() {
      this.$refs.form.validate(async (res) => {
        if (res) {
          try {
            const { date, status, ...rest } = this.musicForm;
            let obj = {
              ...rest,
              status,
            };
            // 是否有乐保
            if (status == 1) {
              if (this.operationData && this.operationData.startTime) {
                obj.startTime = this.operationData.startTime;
              } else {
                obj.startTime = dayjs().format("YYYY-MM-DD HH:mm") + ":00";
              }
              obj.endTime = date;
            } else {
              obj.startTime = "";
              obj.endTime = "";
            }
            if (this.operationStatus == "create") {
              const res = await addStudentInstrument(obj);
              this.$message.success("添加成功");
            } else if (this.operationStatus == "update") {
              const res = await updateStudentInstrument(obj);
              this.$message.success("修改成功");
            }
            this.$emit("close");
            this.$emit("getList");
          } catch (e) {
            console.log(e);
          }
        }
      });
    },
    remoteMethod(query) {
      if (query !== "") {
        this.remoteLoading = true;
        // 发请求搜索
        const url = "/api-web/studentManage/queryStudentList";
        const options = {
          method: "post",
          headers: {
            Authorization: getToken(),
            tenantId: getTenantId(),
          },
          data: {
            rows: 999999,
            search: query,
          },
          url,
        };
        this.remoteLoading = true;
        // this.studentList = []
        axios(options).then((res) => {
          this.remoteLoading = false;
          let result = res.data;
          if (result.code == 200) {
            // Array.prototype.splice.apply(this.studentList, result.data.rows);
            if (result.data.rows && result.data.rows.length > 0) {
              result.data.rows.forEach((item) => {
                this.studentList.unshift(item);
              });
              this.studentList = this.deweight(this.studentList, "studentId");
            }
            // this.studentList = this.studentList.concat(result.data.rows);
          }
        });
      }
    },
    // 制定属性去重
    deweight(arr, key) {
      let res = [];
      arr.forEach((item) => {
        let list = [];
        res.forEach((resitem) => {
          list.push(resitem[key]);
        });
        if (list.indexOf(item[key]) === -1) {
          res.push(item);
        }
      });
      return res;
    },
  },
};
</script>
<style lang="scss" scoped>
  .width100 {
    width: 100%!important;
  }
</style>
