<template>
<el-dialog :title="title" :visible.sync="dialogVisible">
  <el-form :model="form" :rules="rules" ref="form" label-width="100px">
    <el-tabs v-model="tabName" type="card"  @tab-click="handleClick">
      <el-tab-pane label="基础信息设置" name="first" v-if="dialogStatus=='infoUpdate' || dialogStatus=='create'">
          <el-form-item label="公司全称" prop="name">
            <el-input v-model="form.name" placeholder="输入公司全称"></el-input>
          </el-form-item>

          <el-form-item label="公司简称" prop="companyName">
            <el-input v-model="form.companyName" placeholder="输入公司简称"></el-input>
          </el-form-item>

          <el-form-item label="公司状态" prop="status">
            <el-select v-model.number="form.status" placeholder="请选择公司状态">
              <el-option v-for="(val, key, index) in companyStatusAndCode " :key="val.code" :label="val.val"
                         :value="val.code"></el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="所属地区" prop="zoneId">
            <el-select class="filter-item" v-model="form.zoneId" placeholder="请选择" @change="getProvinceRegionsForm">
              <el-option v-for="val in getAllZoneList" :key="val.id" :label="val.name" :value="val.id"> </el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="省份" prop="addrProvince">
            <el-select v-model.number="form.addrProvince" placeholder="请选择省份（直辖市）" @change="changeProvince">
              <el-option v-for="item in provinceRegions" :key="item.id" :label="item.name" :value="item.id"></el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="城市" prop="addrCity">
            <el-select v-model.number="form.addrCity" placeholder="请选择城市" @change="changeCity">
              <el-option v-for="item in cityRegions" :key="item.id" :label="item.name" :value="item.id"></el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="镇（县）">
            <el-select v-model.number="form.addrTown" placeholder="请选择镇（县）">
              <el-option v-for="item in townRegions" :key="item.id" :label="item.name" :value="item.id"></el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="详细地址">
            <el-input v-model="form.addrDetail" placeholder="请输入详细地址"></el-input>
          </el-form-item>
          <el-form-item label="经度">
            <el-input v-model.number="form.longitude" placeholder="请输入经度"></el-input>
          </el-form-item>

          <el-form-item label="纬度">
            <el-input v-model.number="form.latitude" placeholder="请输入纬度"></el-input>
          </el-form-item>

          <el-form-item label="负责人">
            <el-input v-model="form.leader" placeholder="请输入负责人"></el-input>
          </el-form-item>

          <el-form-item label="负责人电话" prop="leaderContactInfo">
            <el-input v-model="form.leaderContactInfo" placeholder="请输入负责人电话"></el-input>
          </el-form-item>

          <el-form-item label="租车客服电话">
            <el-input v-model="form.vehiceServicePhone" placeholder="请输入租车客服电话"></el-input>
          </el-form-item>

          <el-form-item label="旅游客服电话">
            <el-input v-model="form.tourServicePhone" placeholder="请输入旅游客服电话"></el-input>
          </el-form-item>
          <el-form-item label="app展示">
            <el-radio class="radio" v-model="form.isShow" label="1">是</el-radio>
            <el-radio class="radio" v-model="form.isShow" label="2">否</el-radio>
          </el-form-item>

      </el-tab-pane>
      <el-tab-pane label="公司信息" name="second">
        <el-form-item label="图片" :style="{display:'block'}">
          <el-upload
            class="upload-demo"
            :headers="getHeaderWithToken"
            :action="BASE_API+'/api/universal/file/app/unauth/admin/upload'"
            :on-remove="handleRemove"
            :file-list="fileList2"
            :on-success="handleBannerSuccess"
            list-type="picture">
            <div slot="tip" class="el-upload__tip"><span style="color: red;">建议尺寸：1080*644px</span></div>
            <el-button size="small" type="primary">点击上传</el-button>
          </el-upload>
        </el-form-item>
        <el-form-item label="公司简介" prop="title">
          <el-input v-model="form.describes"  type="textarea"
                    :autosize="{ minRows: 2, maxRows: 4}" placeholder="请输入公司简介"></el-input>
        </el-form-item>
        <el-form-item label="详情介绍" prop="title" v-if="activeName2=='first'">
          <div class="editor-container">
            <UE :editorId="activeName2" :defaultMsg="form.content" :config=config  ref="ue"  @ready="editorReadyEvent"></UE>
          </div>
        </el-form-item>
      </el-tab-pane>
    </el-tabs>
  </el-form>
  <div slot="footer" class="dialog-footer" >
    <i class="el-icon-warning" style="float:left;margin: 10px 0;color:#aaa;">上架后将在子公司 地址页面展示此公司</i>
    <!--<el-button @click="cancel('form')">取 消</el-button>-->
    <el-button v-if="dialogStatus=='create'" type="primary" @click="create('form')">保 存</el-button>
    <el-button v-else-if="dialogStatus == 'companyInfoUpdate'" type="primary" @click="upDateCompany('form')">保 存</el-button><!--公司介绍保存-->
    <el-button v-else-if="dialogStatus == 'infoUpdate'" type="primary" @click="updCompanyInfo('form')">保 存</el-button><!--基础信息保存-->
    <el-button v-if="(dialogStatus=='create' || dialogStatus == 'infoUpdate') && state != 1" type="primary" @click="updCompanyState('form')">上 架</el-button>
    <el-button v-else-if="(dialogStatus=='create' || dialogStatus == 'infoUpdate') && state == 1" type="primary" @click="updCompanyState('form')">下 架</el-button>
  </div>
</el-dialog>
</template>
<style>
  textarea{
    display: none;
  }
  .el-upload-list{
    display: flex;
    flex-wrap: wrap;
  }
  .el-upload-list li{
    width: 100px;
    margin: 10px;
  }
</style>

<script>
  import UE from '../../modal/Ueditor';//百度ue富文本
  import {mapGetters} from 'vuex';
  import ElRow from "element-ui/packages/row/src/row";
  import ElCol from "element-ui/packages/col/src/col";
  import ElFormItem from "../../../../node_modules/element-ui/packages/form/src/form-item.vue";
  import {
    getSonRegionByCodes,
    getRegionByCodes,
  } from 'api/base_info/region/';

  import {
    getSysRegionByIds
  } from 'api/vehicle/vehicleInfo/';
  import {
    getAllZone
  } from 'api/base_info/constant/';
  import {
    addCompany,
    getCompanyDetail,
    updCompanyDetail,
    updCompany
  } from 'api/base_info/branch_company';
  import {
    getToken
  } from 'utils/auth';

  export default {
    components: {
      ElFormItem,
      UE,
      ElCol,
      ElRow},
    props: ["dialogStatus", "title", "row"],
    name: 'companyInfoModal',
    data() {
      return {
        flagProvince: false,//编辑时回显
        flagCity: false,
        flagTown: false,
        state: 2,//("上下架:1-上架；2-下架")
        form: {
          id: undefined,
          companyId: undefined,
          name: undefined,//全称
          branchType: 1,
          status: undefined,
          zoneId: undefined,
          addrProvince: undefined,
          addrCity: undefined,
          addrTown: undefined,
          addrDetail: undefined,
          leader: undefined,
          longitude: undefined,
          latitude: undefined,
          leaderContactInfo: undefined,
          updateTime: undefined,
          vehiceServicePhone: undefined,
          tourServicePhone: undefined,
          content: "",//详细介绍
          isShow: "2",//1：是， 2：否
        },
        rules: {
          status: [
            {
              type: 'integer',
              required: true,
              message: '请输名称',
              trigger: 'blur'
            }
          ],
          zoneId: [
            {
              type: 'integer',
              required: true,
              message: '请选择',
              trigger: 'blur'
            }
          ],
          companyName: [
            {
              required: true,
              message: '请输简称',
              trigger: 'blur'
            },
            {
              min: 0,
              max: 200,
              message: '长度小于 200 个字符',
              trigger: 'blur'
            }
          ],
          name: [
            {
              required: true,
              message: '请输名称',
              trigger: 'blur'
            },
            {
              min: 0,
              max: 200,
              message: '长度小于 200 个字符',
              trigger: 'blur'
            }
          ],
          addrDetail: [
            {
              required: true,
              message: '请输入详细地址',
              trigger: 'blur'
            },
            {
              min: 0,
              max: 200,
              message: '长度小于 200 个字符',
              trigger: 'blur'
            }
          ],
//          leaderContactInfo: [
//            {
//              required: false,
//              message: '请输入联系人电话',
//              trigger: 'blur'
//            },
//            {
//              validator: (rule, value, callback) => {
//                if (!value) {
//                  return true;
//                } else {
//                  const reg = /^[1](([3][0-9])|([4][5,7,9])|([5][0-9])|([6][6])|([7][1,2,3,5,6,7,8])|([8][0-9])|([9][1,8,9]))[0-9]{8}$/
//                  console.log(reg.test(value));
//                  if (reg.test(value)) {
//                    callback();
//                  } else {
//                    return callback(new Error('请输入正确的手机号'));
//                  }
//                }
//              },
//              trigger: 'blur'
//            }
//          ],
          addrProvince: [
            {
              required: true,
              type: 'number',
              message: '请选择省份',
              trigger: 'blur'
            }
          ],
          addrCity: [
            {
              required: true,
              type: 'number',
              message: '请选择城市',
              trigger: 'blur'
            },
            {
              validator: (rule, value, callback) => {
                if (this.$utils.isInteger(this.form.addrProvince) &&
                  value.toString().substr(0, 2) != this.form.addrProvince.toString().substr(0, 2)) {
                  return callback(new Error('请选择省份下相应城市'));
                }
                callback();
              },
              trigger: 'blur'
            }
          ]
        },
        tabName: "first",
        config: {
          initialFrameWidth: null,
          initialFrameHeight: 350
        },
        fileList2:[],//图片
        BASE_API: process.env.BASE_API,
        activeName2: undefined,
        dialogVisible:false,
        allZoneArr:[],//全部片区
        provinceRegions: [],//片区下省份数据
      }
    },
    created() {
      this.activeName2 = undefined;
      if(this.dialogStatus == "create"){
        this.activeName2 = "first";
        this.tabName = "first";
      }else if(this.dialogStatus == "companyInfoUpdate"){
        //公司介绍编辑
        this.tabName = "second";
        this.getInfo();
      } else if(this.dialogStatus == "infoUpdate"){
        //基础信息设置
        this.tabName = "first";
        this.getInfo();
      }
      this.bookRecord_btn_unbook = this.elements['bookRecord:btn_unbook'];
    },
    computed: {
      ...mapGetters([
        'elements',
        'companyStatusAndCode'
      ]),
      /**
       * 获取token
       */
      getHeaderWithToken() {
        return {Authorization: getToken()};
      },
      getAllZoneList(){
        this.allZoneArr = getAllZone();
        return getAllZone();
      },
//      provinceRegions() {
//        return getSonRegionByCodes(1);
//      },
      cityRegions() {
        if (!this.$utils.isInteger(this.form.addrProvince)) {
          return null;
        }
        return getSonRegionByCodes(this.form.addrProvince);
      },
      townRegions() {
        if (!this.$utils.isInteger(this.form.addrCity)) {
          return null;
        }
        return getSonRegionByCodes(this.form.addrCity);
      },
      cityRegions4Query() {
        if (!this.$utils.isInteger(this.listQuery.addrProvince)) {
          return null;
        }
        return getSonRegionByCodes(this.listQuery.addrProvince);
      },
      townRegions4Query() {
        if (!this.$utils.isInteger(this.listQuery.addrCity)) {
          return null;
        }
        return getSonRegionByCodes(this.listQuery.addrCity);
      }
    },
    watch: {
      dialogVisible(newValue, oldValue){
        if(!newValue){
          this.$emit("companyInfoDialogEvent", false);
        }
      },
    },
    mounted() {
      this.dialogVisible = true;
    },
    methods: {
      /**
       * 富文本  营地详情
       * */
      editorReadyEvent(instance){
        let t = this;
        instance.addListener('contentChange', () => {
          t.form.content = instance.getContent();
        });
      },
      /**
       * 根据id获取分公司对应信息
       * */
      getInfo() {
        let t = this;
        this.listLoading = true;
        getCompanyDetail(this.row)
          .then(response => {
            let info = response.data;
            t.form.id= info.id;
            t.state = info.state;
            t.form.companyId = info.companyId;
            t.form.name = info.name;//全称
            t.form.companyName = info.companyName;//简称
            t.form.zoneId = info.zoneId;//简称
            t.form.describes = info.describes;//公司简介
            t.form.content = info.content?info.content: "";//公司详情
            t.form.addrProvince = info.addrProvince;//省-编码
            t.form.addrCity = info.addrCity;//市-编码
            t.form.addrTown = info.addrTown;//县-编码
            t.form.addrDetail = info.addrDetail;//详细地址
            t.form.leader = info.leader;//负责人
            t.form.leaderContactInfo = info.leaderContactInfo;//负责人电话
            t.form.status = info.status;//公司状态
            t.form.latitude = info.latitude;//纬度
            t.form.longitude = info.longitude;//经度
            t.form.vehiceServicePhone = info.vehiceServicePhone;//租车客服电话
            t.form.tourServicePhone = info.tourServicePhone;//旅游客服电话
            t.form.images = info.images;
            t.form.isShow = info.isShow?info.isShow+"": "2";//app展示
            let arr = info.images.split(",");//图片
            let temp = [];
            for(let i = 0; i < arr.length; i++){
              if(arr[i]){
                let p = {
                  url: arr[i]
                }
                temp.push(p);
              }
            }
            t.fileList2 = temp;
            this.activeName2 = "first";
//            t.form = response.data;
//            console.log(response.data);
          })
      },
      /**
       * 上/下架
       * */
      updCompanyState(formName){
        const set = this.$refs;
        let params = {};

        set[formName].validate(valid => {
          if (valid) {
            if(this.state != 1){//上架-验证额外信息
              if(!this.form.addrDetail){
                this.$notify({
                  title: '警告',
                  message: "请输入详细地址",
                  type: 'warning',
                  duration: 2000
                });
                return;
              }
              if(!this.form.longitude){
                this.$notify({
                  title: '警告',
                  message: "请输入经度",
                  type: 'warning',
                  duration: 2000
                });
                return;
              }
              if(!this.form.latitude){
                this.$notify({
                  title: '警告',
                  message: "请输入纬度",
                  type: 'warning',
                  duration: 2000
                });
                return;
              }
              if(this.fileList2.length<=0){
                this.tabName = "second";
                this.$notify({
                  title: '警告',
                  message: "请上传公司图片",
                  type: 'warning',
                  duration: 2000
                });
                return;
              }
              if(!this.form.describes){
                this.tabName = "second";
                this.$notify({
                  title: '警告',
                  message: "请输入公司简介",
                  type: 'warning',
                  duration: 2000
                });
                return;
              }
            }
            console.log(this.form);
            let arr = [];
            this.fileList2.map(function(item){
              arr.push(item.url);
            });
            let provinceObj = this.form.addrProvince?getRegionByCodes([this.form.addrProvince]): [{name:""}];
            let cityObj = this.form.addrCity?getRegionByCodes([this.form.addrCity]):[{name:""}];
            let addrTownObj = this.form.addrTown?getRegionByCodes([this.form.addrTown]):[{name:""}];
            params.state = this.state == 1?2:1;//("上下架:1-上架；2-下架")
            params.images = arr.join(",");
            params.id = this.form.id;
            params.companyId = this.form.companyId;
            params.name=  this.form.name;//全称
            params.companyName = this.form.companyName;//简称
            params.zoneId= this.form.zoneId;//片区id
            params.describes = this.form.describes;//公司简介
            params.content = this.form.content;//公司详情
            params.addrProvince = this.form.addrProvince;//省-编码
            params.provinceName = provinceObj[0].name;//省-名称
            params.addrCity = this.form.addrCity;//市-编码
            params.cityName = cityObj[0].name;//市-名称
            params.addrTown = this.form.addrTown;//县-编码
            params.townName = addrTownObj[0].name;//县-名称
            params.addrDetail = this.form.addrDetail;//详细地址
            params.leader = this.form.leader;//负责人
            params.leaderContactInfo = this.form.leaderContactInfo;//负责人电话
            params.status = this.form.status;//公司状态
            params.latitude=  this.form.latitude;//纬度
            params.longitude = this.form.longitude;//经度
            params.vehiceServicePhone = this.form.vehiceServicePhone;//租车客服电话
            params.tourServicePhone = this.form.tourServicePhone;//旅游客服电话
            params.isShow = this.form.isShow;//app展示
            console.log(params);
            updCompany(params)
              .then(res => {
                if(res.status == 200){
                  this.$notify({
                    title: '成功',
                    message: '操作成功',
                    type: 'success',
                    duration: 2000
                  });
                  this.$emit("companyInfoDialogEvent", true);
                }else{
                  this.$notify({
                    title: '失败',
                    message: res.message,
                    type: 'error',
                    duration: 2000
                  });
                }
              })
          } else {
            return false;
          }
        });
      },
      /**
       * 基础信息-编辑-保存
       * */
      updCompanyInfo(formName){
        const set = this.$refs;
        let params = {};
        set[formName].validate(valid => {
            if (valid) {
              console.log(this.form);
              let arr = [];
              this.fileList2.map(function(item){
                arr.push(item.url);
              });
              let provinceObj = this.form.addrProvince?getRegionByCodes([this.form.addrProvince]): [{name:""}];
              let cityObj = this.form.addrCity?getRegionByCodes([this.form.addrCity]):[{name:""}];
              let addrTownObj = this.form.addrTown?getRegionByCodes([this.form.addrTown]):[{name:""}];
              params.images = arr.join(",");
              params.id = this.form.id;
              params.companyId = this.form.companyId;
              params.name=  this.form.name;//全称
              params.companyName = this.form.companyName;//简称
              params.zoneId= this.form.zoneId;//片区id
              params.describes = this.form.describes;//公司简介
              params.content = this.form.content;//公司详情
              params.addrProvince = this.form.addrProvince;//省-编码
              params.provinceName = provinceObj[0].name;//省-名称
              params.addrCity = this.form.addrCity;//市-编码
              params.cityName = cityObj[0].name;//市-名称
              params.addrTown = this.form.addrTown;//县-编码
              params.townName = addrTownObj[0].name;//县-名称
              params.addrDetail = this.form.addrDetail;//详细地址
              params.leader = this.form.leader;//负责人
              params.leaderContactInfo = this.form.leaderContactInfo;//负责人电话
              params.status = this.form.status;//公司状态
              params.latitude=  this.form.latitude;//纬度
              params.longitude = this.form.longitude;//经度
              params.vehiceServicePhone = this.form.vehiceServicePhone;//租车客服电话
              params.tourServicePhone = this.form.tourServicePhone;//旅游客服电话
              params.isShow = this.form.isShow;//app展示
              console.log(params);
              updCompany(params)
                .then(res => {
                  if(res.status==200){
                    this.$notify({
                      title: '成功',
                      message: '编辑成功',
                      type: 'success',
                      duration: 2000
                    });
                    this.$emit("companyInfoDialogEvent", true);
                  }else{
                    this.$notify({
                      title: '失败',
                      message: res.message,
                      type: 'error',
                      duration: 2000
                    });
                  }
                })
            } else {
              return false;
            }
          });
      },
      /**
       * 公司介绍-编辑-保存
       * */
      upDateCompany(formName){
        if(this.dialogStatus == "companyInfoUpdate"){
          const set = this.$refs;
          let params = {};
          set[formName].validate(valid => {
            if (valid) {
              console.log(this.form);
              let arr = [];
              this.fileList2.map(function(item){
                arr.push(item.url);
              });
              params.images = arr.join(",");
              params.describes = this.form.describes;//公司简介
              params.content = this.form.content;//公司详情
              params.id = this.form.id;
              console.log(params);
              updCompanyDetail(params)
                .then(res => {
                  if(res.status==200){
                    this.$notify({
                      title: '成功',
                      message: '编辑成功',
                      type: 'success',
                      duration: 2000
                    });
                    this.$emit("companyInfoDialogEvent", false);
                  }else{
                    this.$notify({
                      title: '失败',
                      message: res.message,
                      type: 'error',
                      duration: 2000
                    });
                  }
                })
            } else {
              return false;
            }
          });
        }
      },

      /**
       * 添加
       **/
      create(formName) {
        const set = this.$refs;
        let params = {};
        set[formName].validate(valid => {
          if (valid) {
            console.log(this.form);
            let arr = [];
            this.fileList2.map(function(item){
              arr.push(item.url);
            });
            let provinceObj = this.form.addrProvince?getRegionByCodes([this.form.addrProvince]): [{name:""}];
            let cityObj = this.form.addrCity?getRegionByCodes([this.form.addrCity]):[{name:""}];
            let addrTownObj = this.form.addrTown?getRegionByCodes([this.form.addrTown]):[{name:""}];
            params.images = arr.join(",");
            params.name=  this.form.name;//全称
            params.companyName = this.form.companyName;//简称
            params.zoneId= this.form.zoneId;//片区id
            params.describes = this.form.describes;//公司简介
            params.content = this.form.content;//公司详情
            params.addrProvince = this.form.addrProvince;//省-编码
            params.provinceName = provinceObj[0].name;//省-名称
            params.addrCity = this.form.addrCity;//市-编码
            params.cityName = cityObj[0].name;//市-名称
            params.addrTown = this.form.addrTown;//县-编码
            params.townName = addrTownObj[0].name;//县-名称
            params.addrDetail = this.form.addrDetail;//详细地址
            params.leader = this.form.leader;//负责人
            params.leaderContactInfo = this.form.leaderContactInfo;//负责人电话
            params.status = this.form.status;//公司状态
            params.latitude=  this.form.latitude;//纬度
            params.longitude = this.form.longitude;//经度
            params.vehiceServicePhone = this.form.vehiceServicePhone;//租车客服电话
            params.tourServicePhone = this.form.tourServicePhone;//旅游客服电话
            console.log(params);
            addCompany(params)
              .then(res => {
                if(res.status==200){
                  this.$notify({
                    title: '成功',
                    message: '创建成功',
                    type: 'success',
                    duration: 2000
                  });
                  this.$emit("companyInfoDialogEvent", true);
                }else{
                  this.$notify({
                    title: '失败',
                    message: res.message,
                    type: 'error',
                    duration: 2000
                  });
                }
              })
          } else {
            return false;
          }
        });
      },
      /*
      * 切换tab
      * */
      handleClick(tab, event) {
        this.tabName = tab.name;
      },
      /**
       * 删除图片
       * */
      handleRemove(file, fileList){
        let list = [];
        fileList.map(function(item){
          list.push(item.url);
        });
        this.fileList2 = fileList;
        this.form.images = list.join(",");
//        let arr = [];
//        this.form.bannerDTOS.map(function(item){
//          if(item.cover != file.url){
//            arr.push(item);
//          }
//        });
//        this.form.bannerDTOS = arr;
      },
      /**
       * 图片上传
       * **/
      handleBannerSuccess(res, file){
        this.fileList2.push({url:res.data});
      },
      /**
       * 改变省份，清空城市
       * */
      changeProvince(){
        if(!this.flagCity){
          this.flagCity = true;
        } else {
          this.form.addrCity = undefined;
          this.form.addrTown = undefined;
        }
      },
      /**
       * 表单里面根据片区获取省份数据
       * */
      getProvinceRegionsForm(){
        let that = this;
        if(!this.flagProvince){
          this.flagProvince = true;
        } else {
          this.form.addrCity = undefined;
          this.form.addrProvince = undefined;
          this.form.addrTown = undefined;
        }
        if (!this.$utils.isInteger(this.form.zoneId)) {
          return null;
        }
        this.allZoneArr.map(function(item){
          if(item.id == that.form.zoneId){
            getSysRegionByIds(item.provinceIds).then(response => {
              let listRs = undefined;
              if (!that.$utils.isEmpty(response.data)) {
                listRs = response.data;
              }
              that.provinceRegions = listRs;
            });
          }
        });
      },
      /**
       * 改变城市，清空城镇
       * */
      changeCity(){
        if(!this.flagTown){
          this.flagTown = true;
        } else {
          this.form.addrTown = undefined;
        }
      }
    }
  }
</script>
