<template>
  <div>
    <el-dialog
      class="dialog"
      width="630px"
      :title="title"
      :visible.sync="lookVisible"
      :before-close="onClose"
    >
      <el-form class="elForm" label-position="top" :model="formes" label-width="100px" ref="eidtCamp">
        <el-form-item
          label="训练营标题"
          :rules="[{ required: true, message: '请输入训练营标题' }]"
          prop="name"
        >
          <el-input class="w100" v-model="formes.name"></el-input>
        </el-form-item>
        <el-form-item label="适用分部" prop="organIds" :rules="[{ required: true, message: '请选择分部' }]">
          <el-select style="width: 100% !important;" v-model="formes.organIds" multiple clearable filterable @change="handleChangeOrgan">
            <el-option :label="o.name" :value="o.id + ''" v-for="(o) in organs" :key="o.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="适用乐团" prop="musicGroupIds" :rules="[{ required: true, message: '请选择乐团' }]">
          <el-select style="width: 100% !important;" v-model="formes.musicGroupIds" multiple clearable filterable>
            <el-option :label="o.musicGroupName" :value="o.musicGroupId" v-for="(o) in musicGroups" :key="o.musicGroupId"></el-option>
          </el-select>
        </el-form-item>
        <div class="wrap">
          <el-form-item
            prop="applyTime"
            label="报名时间"
            :rules="[{ required: true, message: '请选择报名时间' }]"
          >
            <el-date-picker
              v-model.trim="formes.applyTime"
              class="w100"
              type="daterange"
              value-format="yyyy-MM-dd"
              @change="
                () => {
                  formes.trainTime = [];
                }
              "
              range-separator="至"
              start-placeholder="报名开始日期"
              end-placeholder="报名结束日期"
              :picker-options="payDate()"
            >
            </el-date-picker>
          </el-form-item>
          <el-form-item
            prop="trainTime"
            label="训练时间"
            :rules="[{ required: true, message: '请选择训练时间' }]"
          >
            <el-date-picker
              v-model.trim="formes.trainTime"
              type="daterange"
              value-format="yyyy-MM-dd"
              class="w100"
              range-separator="至"
              start-placeholder="训练开始日期"
              end-placeholder="训练结束日期"
              :picker-options="payendTimer"
            >
            </el-date-picker>
          </el-form-item>
        </div>

        <div class="wrap">
          <el-form-item label="打卡标准"
            prop="signStandard"
            :rules="[
              { required: true, message: '请输入打卡标准' },
              { pattern: /^[1-9][0-9]*$/, message: '请输入大于0的正整数',}
            ]"
          >
            <el-input placeholder="请输入打卡标准" v-model="formes.signStandard">
              <template slot="append">分钟/天</template>
            </el-input>
          </el-form-item>
          <el-form-item label="达标天数" 
            prop="standardDays"
            :rules="[
              { required: true, message: '请输入最低打卡天数' },
              { pattern: /^[1-9][0-9]*$/, message: '请输入大于0的正整数',}
              ]"
          >
            <el-input placeholder="请输入最低打卡天数" v-model="formes.standardDays">
              <template slot="append">天</template>
            </el-input>
          </el-form-item>
        </div>
        
        <!-- <el-form-item
          label="封面图"
          prop="picUrl"
          :rules="[
            {
              required: true,
              message: '请上传训练营封面图',
              trigger: 'blur',
            },
          ]"
        >
          <upload
            class="uploadImg"
            v-model="formes.picUrl"
            ref="uploadImg"
          ></upload>
          <p style="color: red">格式为jpg、png、gif图片</p>
        </el-form-item> -->
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="onClose">取 消</el-button>
        <el-button type="primary" @click="submitMsg">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import Upload from "@/components/Upload/index";
import { addTrainingCamp, resetTrainingCamp } from "../api";
import { getTimes } from "@/utils";
import { queryEmployeeOrganByUser } from "@/api/systemManage";
import { queryOrganMusicInfos } from "@/api/zeroManager";
let that;
export default {
  name: "eidtCamp",
  components: {
    Upload,
  },
  data() {
    return {
      title: "",
      organs: [], // 当前员工分部列表
      musicGroups: [], // 所选分部的乐团列表
      timer: '',
      formes: {
        id: "",
        name: "",
        picUrl: "",
        applyTime: [],
        trainTime: [],
        organIds: [], // 分部,多选
        musicGroupIds: [], // 适用乐团
        signStandard: null, // 打开标准
        standardDays: null, // 达标天数
      },
      lookVisible: false,
      chioseIdList: null,
      activeRow: null,
    };
  },

  mounted() {
    that = this;
    this.init();
  },
  methods: {
    async init() {
      const res = await queryEmployeeOrganByUser()
      if (Array.isArray(res?.data)){
        this.organs = res.data
      }
    },

    /** 获取分部乐团列表 */
    async getOrganMusicInfos(){
      const organId = (this.formes?.organIds || []).join(',')
      console.log("🚀 ~ organId:", organId)
      if (!organId) return;
      const res = await queryOrganMusicInfos({organId})
      if (Array.isArray(res?.data)){
        this.musicGroups = res.data
      }
    },

    /** 分部选项改变 */
    handleChangeOrgan(){
      this.formes.musicGroupIds = []
      clearTimeout(this.timer)
      this.timer = setTimeout(() => {
        this.getOrganMusicInfos()
      }, 1000)
    },

    openDioag(row) {
      if (row && row.id) {
        this.activeRow = row;
        this.title = "修改训练营";
        this.formes = {
          ...row,
          organIds: row.organIds?.split(','),
          musicGroupIds: row.musicGroupIds?.split(','),
          applyTime: [row.applyStartDate, row.applyEndDate],
          trainTime: [row.trainStartDate, row.trainEndDate],
        };
        this.getOrganMusicInfos()
      } else {
        this.title = "新建训练营";
      }
      this.lookVisible = true;
    },
    onClose() {
      this.activeRow = null
      this.formes = {
        id: "",
        name: "",
        picUrl: "",
        applyTime: [],
        trainTime: [],
        organIds: [], // 分部,多选
        musicGroupIds: [], // 适用乐团
        signStandard: null, // 打开标准
        standardDays: null, // 达标天数
      };
      this.$refs["eidtCamp"].resetFields();
      this.lookVisible = false;
    },
    submitMsg() {
      this.$refs.eidtCamp.validate(async (flag) => {
        if (flag) {
          try {
            if (this.activeRow && this.activeRow.id) {
              let { applyTime, trainTime, organIds,musicGroupIds, ...rest } = this.formes;
              let params = {
                ...rest,
                organIds: organIds?.join(','),
                musicGroupIds: musicGroupIds?.join(','),
                ...getTimes(applyTime, ["applyStartDate", "applyEndDate"]),
                ...getTimes(trainTime, ["trainStartDate", "trainEndDate"]),
              };
              const res = await resetTrainingCamp({ ...params });
              this.$message.success("修改成功");
              this.onClose();
              this.$emit("getList");
            } else {
              let { applyTime, trainTime, organIds,musicGroupIds, ...rest } = this.formes;
              let params = {
                ...rest,
                organIds: organIds?.join(','),
                musicGroupIds: musicGroupIds?.join(','),
                ...getTimes(applyTime, ["applyStartDate", "applyEndDate"]),
                ...getTimes(trainTime, ["trainStartDate", "trainEndDate"]),
              };
              const res = await addTrainingCamp({ ...params });
              this.$message.success("新建成功");
              this.onClose();
              this.$emit("getList");
            }
          } catch (e) {
            console.log(e);
          }
        }
      });
    },
    getName(val) {
      this.formes.fileName = val.data.name;
    },
    payDate() {
      let self = this;
      return {
        firstDayOfWeek: 1,
        disabledDate(time) {
          return time.getTime() + 86400000 < new Date().getTime();
        },
      };
    },
  },
  computed: {
    payendTimer: () => {
      return {
        firstDayOfWeek: 1,
        disabledDate(time) {
          if (Array.isArray(that.formes.applyTime) && that.formes.applyTime[1]) {
            return (
              time.getTime() <=
              new Date(that.formes.applyTime[1]).getTime()
            );
          } else {
            return time.getTime() <= new Date().getTime();
          }
        },
      };
    },
  },
};
</script>
<style lang="scss" scoped>
@import '@/styles/custom.scss';
.w100 {
  width: 100%;
}

.wrap{
  display: flex;
  align-items: center;
  ::v-deep .el-form-item:not(:last-child){
    margin-right: 20px;
    
  }
  .el-form-item{
    flex: 1;
  }
  ::v-deep{
    .el-range-separator{
      padding: 0;
    }
  }
}
</style>
