<template>
  <div class="main-contain">
    <div  class="position">
      <bread-crumb :crumbs='crumbs'></bread-crumb>
    </div>
    <div class="app-container " >
      <el-form ref="form" :model="form" label-width="80px" id="edit-org-info-form" v-loading="formloading" :element-loading-text="loadingText" class="clearfix" :popper-append-to-body="false" >
        <el-row >
          <el-col :span="24"  >
            <el-form-item label="机构名称:" prop="org_name">
                <el-input v-model="form.org_name" placeholder="机构名称" ></el-input>
            </el-form-item>
            <el-form-item label="联系人姓名:" prop="contact_name">
                <el-input v-model="form.contact_name" placeholder="联系人姓名" ></el-input>
            </el-form-item>
            <el-form-item label="机构介绍:" prop="org_introduction">
                <!-- <el-input type="textarea" :autosize="{ minRows: 2, maxRows: 4}" placeholder="机构介绍" v-model="form.org_introduction">  </el-input> -->
                <keep-alive>
                <neditor ref="neditor" 
                    id="editor" 
                    v-bind:r_content="form.org_introduction">
                </neditor>
            </keep-alive>
            </el-form-item>
            <el-form-item label="机构头像:" prop="org_logo">
                <el-upload
                    v-loading="uploading"
                    :element-loading-text="loadingText"
                    class="avatar-uploader"
                    :data="uploadData"
                    action="https://upload.qiniup.com"
                    :show-file-list="false"
                    :on-error="handleAvatarError"
                    :on-success="handleAvatarSuccess"
                    :before-upload="beforeAvatarUpload">
                    <img v-if="form.org_logo" :src="form.org_logo" class="avatar">
                    <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                </el-upload>
            </el-form-item>
            <el-form-item label="机构地区:" prop="org_area">
                <el-select v-model="form.province" clearable filterable placeholder="请选择" @change="changeProvince">
                    <el-option
                    v-for="item in provinces"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id">
                    </el-option>
                </el-select>
                <el-select v-model="form.city" v-show="form.province&&citys.length>0" clearable filterable placeholder="请选择" @change="changeCity">
                    <el-option
                    v-for="item in citys"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id">
                    </el-option>
                </el-select>
                <el-select v-model="form.district" v-show="form.city&&districts.length>0" clearable filterable placeholder="请选择">
                    <el-option
                    v-for="item in districts"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id">
                    </el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="机构地址:" prop="address">
                <el-input v-model="form.address" placeholder="机构地址" ></el-input>
            </el-form-item>
            <el-form-item label="机构类型:" prop="org_type">
                <el-select v-model="form.parent_type" clearable placeholder="请选择" @change="changeParentType" >
                    <el-option
                    v-for="item in orgtypes"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id">
                    </el-option>
                </el-select>
                <el-select v-model="form.child_type" v-show="form.parent_type&&childtypes.length>0" clearable placeholder="请选择" @change="changeChildType">
                    <el-option
                    v-for="item in childtypes"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id">
                    </el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="机构电话:" prop="telephone">
                <el-input v-model="form.telephone" placeholder="机构电话" ></el-input>
            </el-form-item>
            <el-form-item label="营业状态:" prop="operating_state">
                <el-radio-group v-model="form.operating_state" >
                    <el-radio v-for="item in operatingStateOptions" :key="item.value" :label="item.value" :value="item.value" >{{item.label}}</el-radio>
                </el-radio-group>
            </el-form-item>
            <el-form-item label="营业时间:" prop="business_time">
                <el-input v-model="form.business_week" placeholder="营业时间" style="width:48%"></el-input> 
                <el-input v-model="form.business_time" placeholder="营业时间" style="width:48%"></el-input>
            </el-form-item>
            <el-form-item label="" prop="business_time">
                <el-checkbox-group v-model="form.business_week_select"   @change="handleChangeWeek">
                    <el-checkbox v-for="(item, index) in weekOptions" :label="item" :key="index" :value="item" >{{item}}</el-checkbox>
                </el-checkbox-group>
            </el-form-item>
            
            <el-form-item label="上午:" prop="business_time">
                <el-radio-group v-model="form.business_time_shange" @change="handleChangeTime">
                    <el-radio v-for="(item, index)  in shangOptions" :key="index" :label="item" :value="item" >{{item}}</el-radio>
                </el-radio-group>
            </el-form-item>
            
            <el-form-item label="下午:" prop="business_time_xia">
                <el-radio-group v-model="form.business_time_xia" @change="handleChangeTime">
                    <el-radio v-for="(item, index)  in xiaOptions" :key="index" :label="item" :value="item" >{{item}}</el-radio>
                </el-radio-group>
            </el-form-item>

            <el-form-item label="服务病种:" prop="illness">
                <el-checkbox-group v-model="form.illness_list"  @change="handleChangeIllness">
                    <el-checkbox v-for="item in illnessOptions" :label="item.id" :key="item.id" :value="item.id" >{{item.illness_name}}</el-checkbox>
                </el-checkbox-group>
            </el-form-item>
            <el-form-item label="机构图册:" prop="gallery">
                <el-upload
                    v-loading="guploading"
                    :data="uploadData"
                    action="https://upload.qiniup.com"
                    list-type="picture-card"
                    :file-list="fileList"
                    :on-remove="handleRemove"
                    :on-error="handleGalleryError"
                    :on-success="handleGallerySuccess"
                    :before-upload="beforeGalleryUpload">
                    <i class="el-icon-plus"></i>
                </el-upload>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :span="24">
          <el-col :span="24" align="right" >
            <el-form-item>
                <el-button @click="$router.back(-1)" icon="el-icon-refresh" size="small">取消</el-button>
                <el-button  @click="submitForm"  size="small" type="primary" icon="el-icon-setting" >保存</el-button>
            </el-form-item>
          </el-col>
        </el-row>

      </el-form>

    </div>
  </div>

</template>

<script>
import { getToken } from '@/api/qiniu'
import {GetOrgInfo,SaveOrgGallery,DeleteOrgGallery,EditOrgInfo} from '@/api/org/orginfo';
import {GetDistrictsByUpid} from '@/api/district';
import { getFileExtension} from '@/utils/tools'
import Neditor from '@/components/Neditor'
  import BreadCrumb from '@/xt_pages/components/bread-crumb'
  export default {
    name: 'orginfo',
    data() {
      return {
        crumbs: [
          { path: false, name: '机构信息' },
        ],
        qiniuDomain: 'https://images.shengws.com/',
        formloading:false,
        uploading:false,
        guploading:false,
        formsubmit:false,
        loadingText:'',
        illnessList:[],
        fileList:[],
        provinces:[],
        citys:[],
        districts:[],
        orgtypes:[],
        orgtypesMap:{},
        childtypes:[],
        uploadData: { token: '', key: '' },
        operatingStateOptions: [{ value: 1, label: '正常营业' }, { value: 2, label: '暂未营业' }],
        weekOptions:["星期一", "星期二", "星期三", "星期四", "星期五", "星期六", "星期天"],
        shangOptions:['1:00','2:00','3:00','4:00','5:00','6:00','7:00','8:00','9:00','10:00','11:00','12:00'],
        xiaOptions:['13:00','14:00','15:00','16:00','17:00','18:00','19:00','20:00','21:00','22:00','23:00','24:00'],
        illnessOptions:[],
        form:{
            org_name:'',
            contact_name:'',
            org_introduction:'',
            org_logo:'',
            province:'',
            city:'',
            district:'',
            address:'',
            parent_type:'',
            child_type:'',
            org_type:'',
            telephone:'',
            operating_state:'',
            business_week:'',
            business_week_select:[],
            business_time_shange:'',
            business_time_xia:'',
            business_time:'',
            illness:'',
            illness_list:[],
            org_gallery:[],
        },
            myConfig: {
            // 如果需要上传功能,找后端小伙伴要服务器接口地址
            serverUrl: '/api/web/upload/ueditor',
            // 你的UEditor资源存放的路径,相对于打包后的index.html
            UEDITOR_HOME_URL: '/NEditor/',
            // 编辑器不自动被内容撑高
            autoHeightEnabled: false,
            // 初始容器高度
            initialFrameHeight: 240,
            // 初始容器宽度
            initialFrameWidth: '100%',
            // 关闭自动保存
            enableAutoSave: false
        },
        
      }
    },
    components: {
        Neditor,
      BreadCrumb
    },
    computed: {
      
    },
    created() {
        this.formloading = true;
        this.loadingText = '加载中...';
        this.GetOrgInfo();
    },
    methods: {
        
        handleChangeIllness(values){
            this.form.illness = values.join(',');
        },
        handleChangeWeek(values) {
            var selectweek = [];
            for (const index in values) {
                var item = {id:this.weekOptions.indexOf(values[index]), name:values[index]};
                selectweek.push(item);
            }
            
            if(selectweek.length==0) {
                this.form.business_week = '';
            }else if(selectweek.length==1) {
                this.form.business_week = selectweek[0];
            }else {
                selectweek = selectweek.sort(function (a,b) {
                    return a.id-b.id;
                });
                var blen = selectweek.length;
                if (blen == (selectweek[blen-1].id - selectweek[0].id + 1)) {
                    this.form.business_week = selectweek[0]["name"] + ' — ' + selectweek[blen-1]["name"];
                }else {
                    var tem = [];
                    for (const index in selectweek) {
                        tem.push(selectweek[index].name);
                    }
                    this.form.business_week = tem.join("、")
                }
               
            }
        },
        handleChangeTime(t){
            if(this.form.business_time_shange.length>0 && this.form.business_time_xia.length>0) {
                this.form.business_time = '上午'+this.form.business_time_shange+"—下午"+this.form.business_time_xia;
            }else if (this.form.business_time_shange.length>0) {
                this.form.business_time = '上午'+this.form.business_time_shange;
            }else if (this.form.business_time_xia.length>0) {
                this.form.business_time = "下午"+this.form.business_time_xia;
            }else {
                this.form.business_time = '';
            }
        },
        handleAvatarError(err, file, fileList) {
            this.$message.error(err);
            this.uploading = false;
            return false
        },
        handleAvatarSuccess(res, file) {
            this.form.org_logo = this.qiniuDomain + res.url;
            this.uploading = false;
        },
        beforeAvatarUpload(file) {
            var fileType = file.type
            const isJPG = fileType.indexOf('image') > -1
            const isLt2M = file.size / 1024 / 1024 < 2

            if (!isJPG) {
                this.$message.error('只能上传图片')
                return false
            }
            if (!isLt2M) {
                this.$message.error('上传头像图片大小不能超过 2MB!')
                return false
            }

            var date = new Date()
            var ext = getFileExtension(file.name)
            var key = "" + date.getFullYear() + (date.getMonth() + 1) + date.getDate() + date.getHours()  + date.getMinutes()  + date.getSeconds()  +'_o_' + file.uid + '.' + ext;
            this.uploading = true;
            this.loadingText = '机构头像上传中'

            const _self = this
            return new Promise((resolve, reject) => {
                getToken().then(response => {
                    const token = response.data.data.uptoken
                    _self._data.uploadData.token = token
                    _self._data.uploadData.key = key
                    resolve(true)
                }).catch(err => {
                    reject(false)
                    this.uploading = false;
                })
            })
        },
        handleGalleryError(err, file, fileList) {
            this.$message.error(err);
            this.guploading = false;
            return false
        },
        handleGallerySuccess(res, file) {
            var data = {type:1, url: this.qiniuDomain + res.url};
            SaveOrgGallery(data).then(response=>{
                var res = response.data;
                if (res.state==1) {
                    this.$message.success('上传成功');
                }else {
                    this.$message.error('上传失败');
                }
            }).catch(e=>{});
            this.guploading = false;
        },
        beforeGalleryUpload(file) {
            var fileType = file.type
            const isJPG = fileType.indexOf('image') > -1
            const isLt100M = file.size / 1024 / 1024 < 100

            if (!isJPG) {
                this.$message.error('只能上传图片')
                return false
            }
            if (!isLt100M) {
                this.$message.error('上传图片大小不能超过 100MB!')
                return false
            }

            var date = new Date()
            var ext = getFileExtension(file.name)
            var key = ""+date.getFullYear() + (date.getMonth() + 1) + date.getDate() + date.getHours()  + date.getMinutes()  + date.getSeconds()  +'_g_' + file.uid + '.' + ext;
            this.guploading = true;
            this.loadingText = '机构图册上传中'

            const _self = this
            return new Promise((resolve, reject) => {
                getToken().then(response => {
                    const token = response.data.data.uptoken
                    _self._data.uploadData.token = token
                    _self._data.uploadData.key = key
                    resolve(true)
                }).catch(err => {
                    reject(false)
                    this.guploading = false;
                })
            })
        },

        handleRemove(file, fileList) {
            DeleteOrgGallery(file.id).then(response=>{
                var res = response.data;
                if(res.state==1) {
                    this.$message.success('删除成功');
                }else {
                    this.$message.error('删除失败');
                }
            }).catch(e=>{});
            console.log("handleRemove",file, fileList);
        },
        GetOrgInfo(){
            GetOrgInfo().then(response=>{
                var res = response.data;
                if (res.state === 1) {
                    this.form.org_name = res.data.orginfo.org_name;
                    this.form.contact_name = res.data.orginfo.contact_name;
                    this.form.org_introduction = res.data.orginfo.org_introduction;
                    this.form.org_logo = res.data.orginfo.org_logo;
                    this.form.province = res.data.orginfo.province;
                    this.form.city = res.data.orginfo.city;
                    this.form.district = res.data.orginfo.district;
                    this.form.address = res.data.orginfo.address;
                    this.form.org_type = res.data.orginfo.org_type;
                    this.form.telephone = res.data.orginfo.telephone;
                    this.form.operating_state = res.data.orginfo.operating_state;
                    this.form.business_week = res.data.orginfo.business_week;
                    this.form.business_week_select = [];
                    this.form.business_time = res.data.orginfo.business_time;
                    this.form.business_time_shange = '';
                    this.form.business_time_xia = '';
                    this.form.illness = res.data.orginfo.illness;
                    this.form.illness_list = [];
                    this.form.org_gallery = res.data.orginfo.org_gallery;
                    this.fileList = [];
                    for (const index in this.form.org_gallery) {
                        var image = {id:this.form.org_gallery[index].id, name:this.form.org_gallery[index].id, url: this.form.org_gallery[index].type==1?this.form.org_gallery[index].url:this.form.org_gallery[index].url+'?vframe/jpg/offset/0/w/100/h/100'};
                        this.fileList.push(image);
                    }

                    var illness = res.data.orginfo.illness.split(',');
                    for (const index in illness) {
                        var iid = parseInt(illness[index]);
                        if (isNaN(iid) || iid<=0) {
                            continue;
                        }
                        this.form.illness_list.push(iid);
                    }
                    var business_week = this.form.business_week;
                    var business_week_tem = business_week.split(" — ");
                    if(business_week_tem.length==2) {
                        var fromIndex = this.weekOptions.indexOf(business_week_tem[0]);
                        var toIndex = this.weekOptions.indexOf(business_week_tem[1]);
                        if(fromIndex>=0 && toIndex>=0) {
                            for (const index in this.weekOptions) {
                                if(index>=fromIndex && index <= toIndex) {
                                    this.form.business_week_select.push(this.weekOptions[index]);
                                }
                            }
                        }
                    }else {
                        business_week_tem = business_week.split("、");
                        for (const index in business_week_tem) {
                            if(business_week_tem[index].length>0) {
                                this.form.business_week_select.push(business_week_tem[index]);
                            }
                        }
                    }
                    var business_time = this.form.business_time;
                    var business_time_tem = business_time.split("—");
                    if(business_time_tem.length==2) {
                        this.form.business_time_shange = business_time_tem[0].substring(2);
                        this.form.business_time_xia = business_time_tem[1].substring(2);
                    }else {
                        var selectTime = business_time_tem[0].substring(2);
                        if(this.shangOptions.indexOf(selectTime)>-1) {
                            this.form.business_time_shange = selectTime;
                        }else if(this.xiaOptions.indexOf(selectTime)>-1) {
                            this.form.business_time_xia = selectTime;
                        }
                    }

                    this.provinces = res.data.provinces;
                    this.citys = res.data.citys?res.data.citys:[];
                    this.districts = res.data.districts?res.data.districts:[];

                    this.orgtypes = [];
                    this.orgtypesMap ={},
                    this.childtypes = [];
                    var orgtypes = res.data.orgtypes;
                    for (const index in orgtypes) {
                        if(orgtypes[index].pid>0) {
                            if(!(orgtypes[index].pid in this.orgtypesMap)) {
                                this.orgtypesMap[orgtypes[index].pid] = [];
                            }
                            this.orgtypesMap[orgtypes[index].pid].push(orgtypes[index]);
                            if(orgtypes[index].id == this.form.org_type) {
                                this.form.child_type = orgtypes[index].id;
                                this.form.parent_type = orgtypes[index].pid;
                            }
                        }else {
                            this.orgtypes.push(orgtypes[index]);
                            if(orgtypes[index].id == this.form.org_type) {
                                this.form.parent_type = orgtypes[index].id;
                            }
                        }
                    }
                    if (this.form.parent_type in this.orgtypesMap) {
                        this.childtypes = this.orgtypesMap[this.form.parent_type];
                    }else {
                        this.childtypes = [];
                    }
                    this.illnessOptions = res.data.illness?res.data.illness:[];
                    this.formloading = false;
                } else {
                    this.$message.error(resp.msg)
                }
            }).catch(e=>{

            })
        },
         myTrim(x) {
            return x.replace(/^\s+|\s+$/gm,'');
        },
        changeProvince(id) {
            this.citys = [];
            this.districts = [];
            this.form.city = '';
            this.form.district = '';
            var upid = parseInt(id);
            if (isNaN(upid) || upid<=0) {
                return false;
            }
            GetDistrictsByUpid({id:upid}).then(response=>{
                var res = response.data;
                if(res.state===1) {
                    this.citys = res.data.citys?res.data.citys:[];
                }
            }).catch(e=>{

            })
        },
        changeCity(id) {
            this.districts = [];
            this.form.district = '';
            var upid = parseInt(id);
            if (isNaN(upid) || upid<=0) {
                return false;
            }
            GetDistrictsByUpid({id:upid}).then(response=>{
                var res = response.data;
                if(res.state===1) {
                    this.districts = res.data.citys?res.data.citys:[];
                }
            }).catch(e=>{

            })
        },
        changeParentType(id) {
            id = parseInt(id);
            this.childtypes = [];
            this.form.child_type = '';
            this.form.org_type = 0;

            if (isNaN(id) || id<=0) {
                return false;
            }
            if(id in this.orgtypesMap) {
                this.childtypes = this.orgtypesMap[id];
            }else{
                this.childtypes = [];
            }
            
            this.form.org_type = id;

        },
        changeChildType(id) {
            this.form.org_type = id;
        },
        submitForm(){
            this.form.org_introduction = this.$refs.neditor.content;
            this.formloading = true;
            this.formsubmit = true;
            this.loadingText = '正在保存...';
            EditOrgInfo(this.form).then(response=>{
                var res = response.data;
                if(res.state==1) {
                    this.$store.dispatch("ModifyOrgInfo", { org_name: this.form.org_name, contact_name: this.form.org_name })
                    
                    this.$message.success("修改成功");
                }else {
                    this.$message.error(res.msg);
                }
                
                this.formloading = false;
                this.formsubmit = false;
            }).catch(e=>{

                this.formloading = false;
                this.formsubmit = false;
            })
        },
    }
  }
</script>

<style rel="stylesheet/scss" >

  #edit-org-info-form .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  #edit-org-info-form .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  #edit-org-info-form .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  #edit-org-info-form .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
</style>

