<template>
  <div class="base-form">
    <div class="form">
      <Form :label-width="86" :rules="rules" :model="form" ref="form">
        <Row :gutter="90">
          <i-col :span="12" class="">
            <FormItem label="公司名称" prop="companyName">
              <Input type="text" size="large" v-model="form.companyName" :disabled="isDetail" />
            </FormItem>
          </i-col>
          <i-col :span="12" class="">
            <FormItem label="所属行业" prop="tradeName">
              <i-select size="large" v-model="form.tradeName" @on-change="changeCompanyType" :disabled="isDetail">
                <i-option v-for="item in industryList" :key="item.id" :value="item.name">{{ item.name }}</i-option>
              </i-select>
              <!-- <Input type="text" size="large" v-model="form.companyType" :disabled="isDetail" /> -->
            </FormItem>
          </i-col>
          <i-col :span="12" class="">
            <FormItem label="成立时间" prop="registerDate1">
              <Date-picker v-model="form.registerDate1" type="year" size="large" placeholder=""  :disabled="isDetail" @on-change="changeDate"></Date-picker>
            </FormItem>
          </i-col>
          <i-col :span="12" class="">
            <FormItem label="员工人数" prop="staffNum">
              <Input type="text" size="large" v-model="form.staffNum" :disabled="isDetail" />
            </FormItem>
          </i-col>
          <i-col :span="12" class="">
            <FormItem label="注册资金" prop="registerFund">
              <Input type="text" size="large" v-model="form.registerFund"  :disabled="isDetail"/>
            </FormItem>
          </i-col>
          <i-col :span="12" class="">
            <FormItem label="主要产品" prop="mainProduct">
              <Input type="text" size="large" v-model="form.mainProduct" :disabled="isDetail" />
            </FormItem>
          </i-col>
          <i-col :span="12" class="">
            <FormItem label="公司网址">
              <Input type="text" size="large" v-model="form.companyWebsite" :disabled="isDetail" />
            </FormItem>
          </i-col>
          <i-col :span="24" class="">
            <FormItem label="公司地址">
              <template>
                <Input size="large" v-model="form.companyAddress" :disabled="isDetail" />
                <Button size="large" type="primary" style="margin-left:15px" @click="searchAddress" v-if="!isDetail">查找</Button>
                <qqMap ref="map" city="珠海" :latitude="form.latitude" :longitude="form.longitude" @clickMap="clickMap" v-if="!isDetail" />
              </template>
            </FormItem>
          </i-col>
          <i-col :span="24" class="">
            <FormItem label="公司简介" class="textarea-w">
              <Input type="textarea" size="large" v-model="form.companyDesc" :disabled="isDetail" maxlength="200" :show-word-limit="!isDetail" />
            </FormItem>
          </i-col>
          <i-col :span="24" class="">
            <FormItem label="公司logo">
              <picUpload  ref="logoUpload" tips="只能上传jpg/png文件，且不超过500kb" :multiple="false" :limit="1" :preUploads="preLogoUploads" :hasUploads="hasLogoUploads" :hideUpload="isDetail" />
              <!-- <img style="width: 100px;height:100px;" :src="form.companyLogo" v-else> -->
            </FormItem>
          </i-col>
          <!-- <i-col :span="12" class="">
            <FormItem label="资质认证">
              <picUpload tips="只能上传jpg/png文件，且不超过500kb" :multiple="false" :limit="1" />
            </FormItem>
          </i-col> -->
          <i-col :span="24" class="">
            <FormItem label="场景地址">
              <template>
                <Input type="text" size="large" v-model="vrLink" :disabled="isDetail" />
                <Button type="primary" size="large" class="input-btn" @click="modalShow=true" v-if="!isDetail">选择场景</Button>
                <Button type="primary" size="large" :class="`input-btn ${form.sceneNum ? '' : 'not-allow'}`" @click="toEditScene">编辑场景</Button>
              </template>
            </FormItem>
          </i-col>
          <i-col :span="24" class="">
            <FormItem label="讲解人员">
              <template>
                <div class="guide-info">
                  <p class="guide-name">{{select_guide.name}}</p>
                  <p class="guide-id">{{select_guide.viewerId}}</p>
                  <p class="guide-phone">{{select_guide.phoneNum}}</p>
                  <img v-if="select_guide.avatar" :src="select_guide.avatar" alt="" class="guide-avatar">
                </div>
                <Button type="primary" size="large" @click="guideModalShow=true" v-if="!isDetail">选择/更换</Button>
              </template>
            </FormItem>
          </i-col>
        </Row>
      </Form>
    </div>
    <cModal :show="modalShow"  class="scene-modal" :width="960" title="添加/选择场景" @close="modalShow=false" @submit="changeScene">
      <template>
        <tables 
          :data-api="fetchAllScene"
          :columns="tableColumns"
          placeholder="场景名称"
        />
        <div style="height:20px"></div>
      </template>
    </cModal>
    <cModal :show="guideModalShow"  class="scene-modal" :width="960" title="选择讲解员" @close="guideModalShow=false" @submit="changeGuide">
      <template>
        <tables 
          :data-api="getGuideList"
          :columns="guideTableColumns"
          placeholder="讲解员"
          ref="guideTable"
        />
        <div style="height:20px"></div>
      </template>
    </cModal>
  </div>
</template>

<script>
import picUpload from '@/components/upload'
import cModal from '@/components/Modal'
import tables from 'components/tables'
import * as CompanyApi from '@/api/company'
import { getGuideList, getGuideById } from '@/api/guide'
import { searchPlaceByKeyword } from '@/api/qqmap'
import qqMap from '@/components/map'
import { getToken } from '@/libs/token'

export default {
  props: {
    form: Object,
    isDetail: Boolean
  },
  data () {
    return {
      preLogoUploads: [],
      hasLogoUploads: [],
      select_scene_num: '',
      select_guide_id: '',
      select_guide: {},
      rules: {
        companyName: [{ required: true, message: '请填写公司名', trigger: 'blur' }],
        tradeName: [{ required: true, message: '请选择所属行业', trigger: 'change'}],
        registerDate1: [{ required: true, message: '请填写成立时间', trigger: 'blur', type: 'date'}],
        staffNum: [{ required: true, message: '请填写员工人数', trigger: 'blur' }],
        registerFund: [{ required: true, message: '请填写注册资金', trigger: 'blur' }],
        mainProduct: [{ required: true, message: '请填写主要产品描述', trigger: 'blur' }],
      },
      tableColumns: [
        {
          align: 'center',
          width: 80,
          render: (h, params ) => h('Checkbox', {
            props: {
              trueValue: params.row.num,
              falseValue: false,
              value: params.row.num === this.select_scene_num ? params.row.num : false
            },
            on: {
              'on-change': (val) => {
                this.select_scene_num = val
              }
            }
          })
        },
        {
          type: 'index',
          title: '序号',
          align: 'center',
          width: 80
        },
        {
          title: '场景名称',
          key: 'sceneName',
          align: 'center'
        },
        {
          title: '分类',
          key: 'title',
          align: 'center',
          render: h => h('div', '其它')
        },
        {
          title: '拍摄时间',
          key: 'createTime',
          align: 'center'
        }
      ],
      guideTableColumns: [
        {
          align: 'center',
          width: 80,
          render: (h, params ) => h('Checkbox', {
            props: {
              trueValue: params.row.viewerId,
              falseValue: false,
              value: params.row.viewerId === this.select_guide_id ? params.row.viewerId : false
            },
            on: {
              'on-change': (val) => {
                this.select_guide_id = val
              }
            }
          })
        },
        {
          type: 'index',
          title: '序号',
          align: 'center',
          width: 80
        },
        {
          title: '头像',
          key: 'avatar',
          align: 'center',
          render: (h, params) => h('img', {
            attrs: {
              style: "width: 40px;height:40px;border-radius: 50%;",
              src: params.row.avatar
            }
          })
        },
        {
          title: '名称',
          key: 'name',
          align: 'center'
        },
        {
          title: '联系方式',
          key: 'phoneNum',
          align: 'center'
        }
      ],
      industryList: [],
      getGuideList,
      modalShow: false,
      guideModalShow: false,
      addressList: []
    }
  },
  components: {
    picUpload,
    cModal,
    tables,
    qqMap
  },
  computed: {
    vrLink: {
      set (val) {
        this.form.vrLink = encodeURIComponent(val)
      },
      get () {
        return decodeURIComponent(this.form.vrLink)
      }
    }
  },
  async mounted () {
    await this.getIndustryList()
    this.$watch('form.companyLogo', function (newVal) {
      if (this.isDetail) {
        this.hasLogoUploads = [{img: newVal}]
      }
    }, {
      immediate: true
    })
    this.$watch('form.guideId', async (newVal) => {
      if (this.isDetail) {
        let res = await getGuideById(this.form.guideId)
        this.select_guide = res.data || {}
      }
    })
  },
  methods: {
    async validate () {
      const valid = await this.$refs['form'].validate()
      if (!valid) {
        this.$Message.error('请完善表单')
      }
      return valid
    },
    async submit () {
      let res = await this.$refs['logoUpload'].uploadfiles()
      console.log(this.hasLogoUploads)
      this.form.companyLogo = res[0]
      this.form.registerDate = new Date(this.form.registerDate).getFullYear()
      console.log(this.hasLogoUploads)
    },
    changeScene () {
      this.vrLink = this.select_scene_num ? `${process.env.VUE_APP_4DKANKAN_URL}/kanzhan.html?m=${this.select_scene_num}` : ''
      this.form.vrLink = this.select_scene_num ? encodeURIComponent(`${process.env.VUE_APP_4DKANKAN_URL}/kanzhan.html?m=${this.select_scene_num}`) : ''
      this.form.sceneNum = this.select_scene_num || ''
      this.modalShow = false
    },
    changeGuide () {
      this.select_guide = this.$refs['guideTable'].tableData.find(item => item.viewerId === this.select_guide_id) || {}
      this.form.guideId = this.select_guide.viewerId
      this.guideModalShow = false
    },
    getIndustryList () {
      CompanyApi.getIndustry({pageSize: 9999}).then(res => {
        this.industryList = res.data.list
      })
    },
    changeCompanyType (value) {
      this.form.tradeName = value
    },
    searchAddress () {
      searchPlaceByKeyword({keyword: this.form.companyAddress}).then(res => {
        this.addressList = res.data
        if (res.data[0]) {
          this.$refs['map'].search(res.data[0].location)
        }
    
      })
    },
    clickMap (value) {
      console.log(value)
      this.form.companyAddress = value.address
      this.form.latitude = value.location.lat
      this.form.longitude = value.location.lng
    },
    changeDate (date) {
      this.form.registerDate = date
    },
    fetchAllScene (data) {
      console.log(data)
      return CompanyApi.fetchAllScene(data).then(res => {
        return {
          data: {
            list: [...res.data.myScene, ...res.data.cooperationScene]
          }
        }
      })
    },
    toEditScene () {
      if (this.form.sceneNum) {
        let kankan = process.env.ENV === 'production' ? `https://4dkankan.com/epc.html?m=${this.form.sceneNum}` : `https://test.4dkankan.com/epc.html?m=${this.form.sceneNum}`
        kankan = `${kankan}&token=${getToken()}`
        window.open(kankan)
      }
    }
  }
}
</script>

<style lang="less">
.base-form {

  .address-detail {
    font-size: 12px;
    color: #909090;
  }
  .ivu-select .ivu-select-dropdown {
    width: 337px;
    overflow: auto;
    overflow-x: hidden;
  }
}
.guide-info {
  width: 380px;
  padding: 12px 15px 16px;
  font-size: 14px;
  background: #161A1A;
  border:1px solid rgba(255,255,255,0.4);
  position: relative;
  line-height: 19px;
  display: inline-block;
  margin-right: 15px;
  min-height: 104px;
  vertical-align: top;
  p {
    margin-bottom: 10px;
  }
  .guide-phone {
    margin-bottom: 0;
  }
  .guide-avatar {
    position: absolute;
    right: 15px;
    top: 15px;
    width: 60px;
    height: 60px;
    border-radius: 50%;
  }
  
}
</style>