<template>
  <div class="app-container">
    <!-- <el-card class="box-card"> -->
    <div slot="header" class="clearfix">
      <div style="display: inline-block;">
        <div v-if="clueForm.consultCount && clueForm.consultCount < 2">
          学员信息
          <span v-if="clueForm.name">-【{{ clueForm.name }}】</span>
        </div>
        <el-popover v-else placement="top-start" trigger="hover">
          <el-table :data="consultRecord">
            <el-table-column width="120" prop="consultTime" label="咨询日期" />
            <el-table-column width="100" prop="consultUserName" label="咨询人" />
          </el-table>
          <el-badge slot="reference" :value="clueForm.consultCount">
            <span>
              学员信息
              <span v-if="clueForm.name">-【{{ clueForm.name }}】</span>
            </span>
          </el-badge>
        </el-popover>
      </div>
      <div style="float: right;">
        <div style="display: inline-block;margin-right: 5px;">
          <template v-if="saveNextShow">
            <el-checkbox v-model="saveNext" />
            <span class="ml5">保存后继续创建下一条</span>
          </template>
        </div>
        <!-- :disabled="!canSubmit" -->
        <el-button class="footer_button" :disabled="!canSubmit" type="primary" @click="clueSubmit">确 定</el-button>
        <el-button class="footer_button" @click="toBackClue">取 消</el-button>
      </div>
    </div>
    <el-divider />
    <div>
      <el-form ref="clueForm" :model="clueForm" :rules="rules" label-width="110px">
        <el-row :gutter="20">
          <el-col :span="8">
            <el-col :span="24">
              <el-form-item label="创建时间" prop="createTime">
                <el-date-picker style="width: 100%;" v-model="clueForm.createTime" value-format="yyyy-MM-dd HH:mm" format="yyyy-MM-dd HH:mm" type="datetime" :disabled="admin!='true'" />
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="线索来源" prop="source">
                <el-select style="width: 100%;" v-model="clueForm.source" placeholder="请选择" clearable>
                  <el-option v-for="dict in sourceOptions" :key="dict.dictValue" :label="dict.dictLabel" :value="dict.dictValue" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="姓名" prop="name">
                <el-input v-model="clueForm.name" placeholder="请输入姓名" />
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="联系方式" prop="phone">
                <el-input v-model="clueForm.phone" placeholder="请输入联系方式" />
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="微信号" prop="weChat">
                <el-input v-model="clueForm.weChat" placeholder="请输入微信号" />
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="跟进人员" prop="followUser">
                <el-select style="width: 100%;" v-model="clueForm.followUser" multiple clearable :disabled="admin != 'true' && clueForm.clueId != undefined">
                  <el-option v-for="dict in userOptions" :key="dict.id" :label="dict.name" :value="dict.id" />
                </el-select>
              </el-form-item>
            </el-col>

            <el-col :span="24">
              <el-form-item label="意向状态" prop="intentionState">
                <el-select style="width: 100%;" v-model="clueForm.intentionState" placeholder="请选择" clearable>
                  <el-option v-for="dict in intentionOptions" :key="dict.dictValue" :label="dict.dictLabel" :value="dict.dictValue">
                    <i class="el-icon-star-on" :style="dict.cssClass" />
                    <span style="float: right; color: #8492a6; font-size: 13px">
                      {{ dict.dictValue }}
                    </span>
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="下次跟进时间" prop="followTime">
                <el-date-picker style="width: 100%;" v-model="clueForm.followTime" value-format="yyyy-MM-dd" format="yyyy-MM-dd" type="date" />
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="是否近期看场地" prop="recentLook">
                <el-radio v-model="clueForm.recentLook" label="是">是</el-radio>
                <el-radio v-model="clueForm.recentLook" label="否">否</el-radio>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="备注" prop="clueMemo">
                <el-input v-model="clueForm.clueMemo" type="textarea" :rows="5" maxlength="10009" />
              </el-form-item>
            </el-col>
            <!-- 跟进记录 -->
            <el-col :span="24" style="margin-top: 20px;">
              <el-form-item label="跟进记录" prop="clueMemo" label-position="top">
                <FollowRecord v-if="clueId" :clueId="clueId" />
              </el-form-item>
            </el-col>

          </el-col>
          <el-col :span="16">
            <div>
              <el-col :span="24" class="mb20 plr20" style="position: relative">
                <PlaceMap ref="placeMap" :placeList="placeList" />
                <div class="address">
                  <el-form-item label="位置" prop="address" label-width="80px">
                    <el-input v-model="clueForm.address" placeholder="请输入位置" disabled>
                      <el-button slot="append" class="p10" icon="el-icon-location-information" @click="handleMapDialog" />
                      <el-button slot="append" class="p10" icon="el-icon-delete-solid" @click="handleRemovePosition" />
                    </el-input>
                  </el-form-item>
                </div>
              </el-col>
            </div>
          </el-col>
        </el-row>
      </el-form>

    </div>
    <!-- </el-card> -->

    <MapDialog v-if="mapDialogVisible" ref="mapDialog" :dialog-visible="mapDialogVisible" @handleMapDialogPoint="handleMapDialogPoint" />

  </div>
</template>

<script>
import { getClueInfo, getConsultRecord, addClue, updateClue, } from '@/api/zs/clue'
import empApi from '@/api/system/employee'
import { getAllPlaces } from '@/api/sch/place'

import PlaceMap from './components/PlaceMap.vue';
import FollowRecord from './components/FollowRecord.vue';
import MapDialog from './components/MapDialog.vue';

export default {
  name: 'ClueForm',
  components: {
    PlaceMap, FollowRecord, MapDialog
  },
  data() {
    return {
      admin: localStorage.getItem('admin'),
      userId: localStorage.getItem('userId'),
      clueId: undefined,
      clueForm: {
        followTime: undefined
      },
      rules: {
        name: { required: true, message: '姓名不为空', trigger: 'blur' },
        phone: [{ required: true, message: '联系方式不为空', trigger: 'blur' },
        { pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/, message: '请输入正确的手机号码', trigger: 'blur' }],
        createTime: { required: true, message: '创建时间不为空', trigger: 'blur,change' },
        consultTime: { required: true, message: '咨询时间不为空', trigger: 'blur,change' },
        source: { required: true, message: '线索来源不为空', trigger: 'blur,change' },
        address: { required: true, message: '位置不为空', trigger: 'blur' },
        intentionState: { required: true, message: '意向状态不为空', trigger: 'blur,change' }
      },
      userOptions: [],//跟进人员
      sourceOptions: [],//线索来源
      intentionOptions: [],//意向状态
      placeList: [],//场地信息
      mapDialogVisible: false,
      consultRecord: [],
      canSubmit: true,
      saveNextShow: true,
      saveNext: false
    };
  },
  created() {
    //获取clueId
    this.clueId = Number(this.$route.params.clueId)
    this.getAllPlaces()
    this.getEmployee();

    this.getClueInfo(this.clueId);
    // 线索来源
    this.getDicts('dm_source').then((response) => {
      this.sourceOptions = response.data;
    });
    // 意向状态
    this.getDicts('dm_intention_state').then((response) => {
      this.intentionOptions = response.data;
    });
  },

  methods: {
    async getClueInfo(clueId) {
      this.resetForm();
      if (clueId === 0)
        return
      this.saveNextShow = false
      this.saveNext = false
      const resp = await getClueInfo(clueId);
      if (resp.code == 200) {
        this.clueForm = { ...resp.data }
        this.handleMapCenter(this.clueForm);
        this.getConsultRecord(this.clueForm.phone);
      }
    },
    resetForm() {
      this.clueForm = {
        clueId: undefined,
        createTime: this.parseTime(new Date(), '{y}-{m}-{d} {h}:{i}'),
        consultTime: undefined,
        source: undefined,
        name: undefined,
        phone: undefined,
        address: undefined,
        intentionState: undefined,
        followInfo: undefined,
        followTime: undefined,
        followUser: [],
        signupInfo: undefined,
        requirement: undefined,
        licenseType: undefined,
        lng: undefined,
        lat: undefined
      }

      if (this.admin == 'false') {
        this.clueForm.followUser.push(Number(this.userId))
      }
    },
    // 查询咨询记录
    getConsultRecord(phone) {
      getConsultRecord({ phone }).then((resp) => {
        if (resp && resp.code === 200 && resp.data) {
          this.consultRecord = resp.data
          if (this.consultRecord && this.consultRecord.length > 0) {
            this.clueForm.consultCount = this.consultRecord.length
          }
        }
      })
    },
    //地图编辑弹框
    handleMapDialog() {
      this.mapDialogVisible = true;
      this.$nextTick(() => {
        this.$refs.mapDialog.initData(this.clueForm);
      });
    },
    //处理地图弹框返回的点
    handleMapDialogPoint(point) {
      console.log("handleMapDialogPoint")
      console.log(point)
      if (point) {
        this.handleMapCenter(point);
      }
    },
    //删除当前地址
    handleRemovePosition() {
      this.clueForm.lng = undefined;
      this.clueForm.lat = undefined;
      this.clueForm.address = undefined;
    },
    //定位地图的中心点
    handleMapCenter(info) {
      this.$nextTick(() => {
        this.$refs.placeMap.setMapCenter(info);
      });
    },
    // 查询不能接收线索的员工
    getEmployee() {
      empApi.getEmployee().then((resp) => {
        if (resp.code === 200) {
          this.userOptions = resp.data;
          // this.userOptions = this.userOptions.filter((item) => {
          //   return item.accept;
          // });
        }
      });
    },
    // 查询场地信息
    async getAllPlaces() {
      const resp = await getAllPlaces({ status: '0' });
      if (resp.code == 200) {
        this.placeList = resp.data.filter((item) => item.schoolShow && item.showInMap);
        this.$nextTick(() => {
          this.$refs.placeMap.handleMarkers(this.placeList);
        });
      }

    },
    //表单提交
    clueSubmit() {
      this.$refs.clueForm.validate(async (valid) => {
        if (valid) {
          this.canSubmit = false
          let resp
          if (this.clueForm.clueId) {
            resp = await updateClue(this.clueForm)
            this.canSubmit = true
            if (resp.code === 200) {
              this.$message.success('修改成功')
              this.toBackClue();
            }
          } else {
            resp = await addClue(this.clueForm)
            this.canSubmit = false
            if (resp.code === 200) {
              if (resp.data && resp.data == 1) {
                this.$message({
                  message: resp.msg,
                  type: 'warning'
                });
              } else {
                this.$message.success('新增成功')

              }
              if (this.saveNext) {
                this.canSubmit = true
                this.resetForm()
              } else {
                this.toBackClue();
              }
            }
          }
        }
      })
    },
    toBackClue() {
      const obj = { path: "/zs/clue" };
      this.$tab.closeOpenPage(obj);
    }

  }
};
</script>

<style lang="scss" scoped>
.address {
  position: absolute;
  left: 30px;
  top: 40px;
  width: 400px;
  background: #fff;
}

::v-deep .el-divider--horizontal {
  margin: 10px 0 !important;
}
</style>
