<template>
  <div class="page">
    <van-form ref="form" @submit="submit" :submit-on-enter="false">
      <van-popover v-model="showPopover" trigger="click">
        <template #reference>
          <van-field
            name="企业名称"
            label="企业名称"
            placeholder="请输入企业名称"
            v-model="form.name"
            :rules="[{ required: true, message: '请填写企业名称' }]"
            @change="like"
          />
        </template>

        <van-cell-group>
          <van-cell
            v-for="(item, index) in list"
            :key="index"
            :title="item"
            @click="choose(item)"
          />
        </van-cell-group>
      </van-popover>
      <van-field
        name="注册号"
        label="注册号/统一社会信用代码"
        placeholder="请输入注册号/统一社会信用代码"
        v-model="form.uscc"
        :rules="[{ required: true, message: '请填写注册号/统一社会信用代码' }]"
      />
      <van-field
        name="是否从事文化艺术类校外培训"
        label="是否从事文化艺术类校外培训"
        :rules="[
          {
            validator: val => {
              return val || val === false;
            },
            message: '请选择'
          }
        ]"
      >
        <template #input>
          <van-radio-group
            v-model="form.engagedInTraining"
            direction="horizontal"
          >
            <van-radio :name="true"> 是</van-radio>
            <van-radio :name="false">否</van-radio>
          </van-radio-group>
        </template>
      </van-field>
      <div style="margin:30px" v-if="!form.id">
        <van-button
          class="submit"
          native-type="button"
          round
          block
          type="info"
          @click="byUscc"
        >
          查询
        </van-button>
      </div>
      <template v-else-if="form.engagedInTraining">
        <van-field
          type="textarea"
          name="经营范围"
          label="经营范围"
          placeholder="请输入经营范围"
          v-model="form.businessScope"
          autosize
        />
        <van-field
          name="企业住所"
          label="企业住所"
          placeholder="请输入企业住所"
          v-model="form.address"
        />
        <van-field
          name="生产经营场所"
          label="生产经营场所"
          placeholder="请输入生产经营场所"
          v-model="form.businessPremise"
        />
        <van-field
          name="生产法人姓名"
          label="生产法人姓名"
          placeholder="请输入生产法人姓名"
          v-model="form.privacyPolicy"
        />
        <!-- <van-field
          type="tel"
          maxlength="11"
          name="生产短信号码"
          label="生产短信号码"
          placeholder="请输入短信号码"
          v-model="form.phone"
        /> -->
        <van-field
          type="digit"
          name="企业联系方式"
          label="企业联系方式"
          placeholder="请输入企业联系方式"
          v-model="form.contactPhone"
        />
        <van-field
          name="所属管区"
          label="所属管区"
          placeholder="请输入所属管区"
          v-model="form.district"
        />
        <van-field
          type="number"
          name="注册资本"
          label="注册资本（万）"
          placeholder="请输入注册资本"
          v-model="form.registeredCapital"
        />
        <van-field
          name="单位性质"
          label="单位性质"
          placeholder="请输入单位性质"
          v-model="form.category"
          readonly
          @click="showType = true"
        />

        <van-action-sheet
          v-model="showType"
          :actions="types"
          cancel-text="取消"
          close-on-click-action
          @select="onSelect"
        />
        <!-- <van-popup v-model="showArea" position="bottom">
  <van-area
    :area-list="areaList"
    @confirm="onConfirm"
    @cancel="showArea = false"
  />
</van-popup> -->

        <van-field
          name="专业种类"
          label="专业种类"
          placeholder="请输入专业种类"
        >
          <template #input>
            <van-checkbox-group v-model="form.specialty" direction="horizontal">
              <van-checkbox
                :name="item"
                v-for="(item, index) in specialtyOptions"
                :key="index"
                >{{ item }}</van-checkbox
              >
              <div class="extra-content">
                <van-checkbox class="extra" name="其他">其他</van-checkbox>
                <van-field
                  v-if="showExtra"
                  class="input"
                  type="text"
                  placeholder="请输入"
                  v-model="extra"
                  size="small"
                />
              </div>
            </van-checkbox-group>
          </template>
        </van-field>
        <van-field
          type="digit"
          name="培训点数量三楼及以下"
          label="培训点数量三楼及以下"
          placeholder="请输入培训点数量三楼及以下"
          v-model="form.trainingSite"
        />
        <van-field
          type="digit"
          name="培训点数量四楼及以上"
          label="培训点数量四楼及以上"
          placeholder="请输入培训点数量四楼及以上"
          v-model="form.trainingSiteFour"
        />
        <van-field
          type="number"
          name="总面积"
          label="总面积（建筑面积）"
          placeholder="请输入总面积（建筑面积）"
          v-model="form.area"
        />
        <van-field
          type="digit"
          name="教室数量"
          label="教室数量"
          placeholder="请输入教室数量"
          v-model="form.classroomNum"
          :rules="[{ required: true, message: '请填写教室数量' }]"
        />

        <div class="panel">
          <van-divider content-position="left">教师人数统计</van-divider>
          <van-field
            type="digit"
            name="专职数量"
            label="专职数量"
            placeholder="请输入专职数量"
            v-model="form.fullTimeNum"
            @change="changeNum"
            :rules="[{ required: true, message: '请填写专职数量' }]"
          />
          <van-field
            type="digit"
            name="兼职数量"
            label="兼职数量"
            placeholder="请输入兼职数量"
            v-model="form.partTimeNum"
            @change="changeNum"
            :rules="[{ required: true, message: '请填写兼职数量' }]"
          />
          <van-field
            type="digit"
            name="教师总数"
            label="教师总数"
            placeholder="请输入教师总数"
            v-model="form.teacherNum"
            :rules="[{ required: true, message: '请填写教师总数' }]"
          />
        </div>
        <div class="panel">
          <van-divider content-position="left">教师专业人数统计</van-divider>

          <van-field
            type="digit"
            name="音乐类"
            label="音乐类"
            placeholder="请输入音乐类"
            v-model="form.musicNum"
            @focus="focusNum('musicNum')"
            @blur="blurNum('musicNum')"
            @input="changeClass($event, 'musicNum')"
            :rules="[
              {
                validator: val => {
                  return !isMore;
                },
                message: '教师总数为' + form.teacherNum
              }
            ]"
          />
          <van-field
            type="digit"
            name="舞蹈类"
            label="舞蹈类"
            placeholder="请输入舞蹈类"
            v-model="form.danceNum"
            @focus="focusNum('danceNum')"
            @blur="blurNum('danceNum')"
            @input="changeClass($event, 'danceNum')"
            :rules="[
              {
                validator: val => {
                  return !isMore;
                },
                message: '教师总数为' + form.teacherNum
              }
            ]"
          />
          <van-field
            type="digit"
            name="美术类"
            label="美术类"
            placeholder="请输入美术类"
            v-model="form.artNum"
            @focus="focusNum('artNum')"
            @blur="blurNum('artNum')"
            @input="changeClass($event, 'artNum')"
            :rules="[
              {
                validator: val => {
                  return !isMore;
                },
                message: '教师总数为' + form.teacherNum
              }
            ]"
          />
          <van-field
            type="digit"
            name="戏剧戏曲"
            label="戏剧戏曲"
            placeholder="请输入戏剧戏曲"
            v-model="form.theatreOperaNum"
            @focus="focusNum('theatreOperaNum')"
            @blur="blurNum('theatreOperaNum')"
            @input="changeClass($event, 'theatreOperaNum')"
            :rules="[
              {
                validator: val => {
                  return !isMore;
                },
                message: '教师总数为' + form.teacherNum
              }
            ]"
          />
          <van-field
            type="digit"
            name="曲艺类"
            label="曲艺类"
            placeholder="请输入曲艺类"
            v-model="form.folkMusicNum"
            @focus="focusNum('folkMusicNum')"
            @blur="blurNum('folkMusicNum')"
            @input="changeClass($event, 'folkMusicNum')"
            :rules="[
              {
                validator: val => {
                  return !isMore;
                },
                message: '教师总数为' + form.teacherNum
              }
            ]"
          />
        </div>

        <van-field
          type="digit"
          name="有教师资格证"
          label="有教师资格证"
          placeholder="请输入有教师资格证"
          v-model="form.qualificationNum"
          :rules="[{ required: true, message: '请填写有教师资格证' }]"
        />
        <van-field
          type="digit"
          name="年培训人数"
          label="年培训人数"
          placeholder="请输入年培训人数"
          v-model="form.traineesPerYearNum"
          :rules="[{ required: true, message: '请填写年培训人数' }]"
        />
        <van-field
          name="是否是艺术水平考级考点"
          label="是否是艺术水平考级考点"
          placeholder="请输入是否是艺术水平考级考点"
        >
          <template #input>
            <van-radio-group v-model="form.examPoint" direction="horizontal">
              <van-radio :name="true"> 是</van-radio>
              <van-radio :name="false">否</van-radio>
            </van-radio-group>
          </template>
        </van-field>
        <van-field
          name="艺术水平考级机构名称"
          label="艺术水平考级机构名称"
          placeholder="请输入艺术水平考级机构名称"
          v-model="form.gradingOrganization"
        />
        <van-field
          type="textarea"
          name="备注"
          label="备注"
          placeholder="请输入备注"
          v-model="form.remark"
        />

        <div class="bottom">
          <van-button
            @click="saveWeb"
            class="preview"
            color="#ffcf6a"
            block
            round
            native-type="button"
            style="margin-right:12px"
            >暂存</van-button
          >
          <van-button
            class="submit"
            round
            block
            type="info"
            native-type="submit"
            >提交</van-button
          >
        </div>
      </template>
    </van-form>

    <van-divider> 技术客服:19951988293</van-divider>
  </div>
</template>

<script>
export default {
  data() {
    return {
      form: {
        examPoint: false
      },
      list: [],
      showPopover: false,
      activeNames: "1",
      isMore: false,
      showType: false,
      types: [
        { name: "企业" },
        { name: "社会组织" },
        { name: "事业单位" },
        { name: "其他" }
      ],
      extra: "",
      specialtyOptions: ["音乐类", "舞蹈类", "美术类", "戏曲戏剧类", "曲艺类"]
    };
  },
  mounted() {
    let data = JSON.parse(
      window.localStorage.getItem("trainingInstitution") || "{}"
    );
    data.specialty = this.setSpecialty(data.specialty);
    this.form = data;
  },
  computed: {
    showExtra() {
      let special = [...this.form.specialty];
      return special.includes("其他");
    }
  },
  methods: {
    onSelect(val) {
      this.form.category = val.name;
    },
    like(info, key = "") {
      this.$toast.loading({
        message: "加载中...",
        forbidClick: true,
        duration: 0
      });
      this.showPopover = false;
      let data = { search: this.form.name, size: 4, query: {} };
      if (key) {
        data.query[key] = this.form[key];
      }
      this.$http
        .post("/trainingInstitution/name", data, { body: "json" })
        .then(res => {
          this.$toast.clear();
          this.list = res.content;
          setTimeout(() => {
            this.$nextTick(() => {
              this.showPopover = true;
            });
          }, 500);
        });
    },
    setSpecialty(specialty) {
      if (specialty) {
        specialty = specialty.split(",");
        specialty.forEach((item, index) => {
          if (!this.specialtyOptions.includes(item)) {
            specialty[index] = "其他";
            this.extra = item;
          }
        });
        return specialty;
      } else {
        return [];
      }
    },
    byUscc() {
      this.$refs.form.validate().then(() => {
        this.$toast.loading({
          message: "加载中...",
          forbidClick: true,
          duration: 0
        });
        this.extra = "";
        this.$http
          .post(
            `/trainingInstitution/byUscc?name=${this.form.name}&uscc=${this.form.uscc}`
          )
          .then(res => {
            res.category = res.category || "";
            res.specialty = this.setSpecialty(res.specialty);
            this.$toast.clear();
            this.form = { ...res, ...this.form };
            if (!this.form.engagedInTraining) {
              this.submit();
            }
          })
          .catch(e => {
            this.$toast(e.error);
          });
      });
    },
    choose(info) {
      this.form.name = info;
      // this.form = { examPoint: false, ...info };
      this.showPopover = false;
    },
    submit() {
      if (!this.form.id) {
        return;
      }
      this.$toast.loading({
        message: "加载中...",
        forbidClick: true,
        duration: 0
      });
      let data = { ...this.form };
      data.specialty.forEach((item, index) => {
        if (!this.specialtyOptions.includes(item)) {
          data.specialty[index] = this.extra;
        }
      });
      data.specialty = data.specialty.filter(item => {
        return item;
      });
      data.specialty = data.specialty.join(",");
      this.$http
        .post("/trainingInstitution/save", data, { body: "json" })
        .then(res => {
          this.$toast.clear();
          window.localStorage.removeItem("trainingInstitution");
          this.$dialog({
            title: "提交成功",
            message: "信息已经提交成功，感谢您的配合。",
            showConfirmButton: false
          });
        })
        .catch(e => {
          this.$toast(e.error);
        });
    },
    saveWeb() {
      let form = { ...this.form };
      form.specialty.forEach((item, index) => {
        if (!this.specialtyOptions.includes(item)) {
          form.specialty[index] = this.extra;
        }
      });
      form.specialty = form.specialty.filter(item => {
        return item;
      });
      form.specialty = form.specialty.join(",");
      let data = JSON.stringify(form);
      window.localStorage.setItem("trainingInstitution", data);
      this.$toast.success("暂存成功");
    },
    changeNum() {
      this.$nextTick(() => {
        this.form.teacherNum =
          Number(this.form.partTimeNum) + Number(this.form.fullTimeNum);
      });
    },
    changeClass(val, label) {
      let keys = {
        musicNum: "音乐类",
        danceNum: "舞蹈类",
        artNum: "美术类",
        theatreOperaNum: "戏剧戏曲",
        folkMusicNum: "曲艺类"
      };
      let total = Number(val);
      Object.keys(keys).forEach(item => {
        if (label !== item) {
          total += Number(this.form[item]);
        }
      });
      if (total > this.form.teacherNum) {
        this.isMore = true;
        this.$refs.form.validate(keys[label]);
      } else {
        this.isMore = false;
      }
    },
    focusNum(key) {
      if (!Number(this.form[key])) {
        this.form[key] = "";
      }
    },
    blurNum(key) {
      this.form[key] = Number(this.form[key]);
    },
    changeExtra(val) {
      console.log(val);
      if (val) {
        this.$refs.extra.focus();
      }
    }
  }
};
</script>

<style lang="less" scoped>
.page {
  position: relative;
  padding-bottom: 100px;
}
/deep/.van-field {
  margin: 16px 16px 0;
  width: calc(100vw - 32px);
  border-radius: 12px;
  flex-direction: column;

  .van-field__label {
    font-size: 18px;
    font-weight: bold;
    color: #313233;
    line-height: 28px;
    width: auto;
  }
  .van-field__value {
    margin-top: 14px;
    font-size: 16px;
    line-height: 32px;
  }
}

.bottom {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  padding: 6px 26px calc(env(safe-area-inset-bottom) + 6px);
  background-color: #fff;
  z-index: 20;

  display: flex;

  .preview {
    min-width: 82px;
    width: 82px;
  }
  .submit {
    flex-grow: 1;
    // margin-left: 13px;
  }
}
.panel {
  padding: 30px 0;
}
.panel + .panel {
  padding-top: 0;
}

.van-checkbox {
  margin-bottom: 5px;
}
.extra-content {
  display: flex;
  align-items: center;
}
.van-divider {
  font-size: 16px;
}

/deep/.input {
  margin: 0;
  width: calc(100vw - 240px);
  border: 1px solid #ccc;
  padding: 0px 12px;
  border-radius: 0;
  .van-field__value {
    margin-top: 0;
    line-height: 24px;
    font-size: 14px;
  }
}

.tips {
}
</style>
