<template>
  <div class="info">
    <el-form v-loading="loading" :model="formData" :rules="rules" ref="ruleForm" label-width="150px" class="custom-form">
      <form-option title="基本信息" :rightButton="rightButton"></form-option>
      <el-row>
        <el-col :span="10">
          <el-form-item label="单位名称" prop="enforce_obj_name">
            <el-input v-model="formData.enforce_obj_name"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="10">
          <el-form-item label="统一社会信用代码" prop="credit_code">
            <el-input v-model="formData.credit_code" @blur="changeCreditCode"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="10">
          <el-form-item label="单位地址" prop="enforce_obj_address">
            <el-input v-model="formData.enforce_obj_address" suffix-icon="el-icon-place"
                      @focus="showMap=true"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="10">
          <el-form-item label="经纬度">
            <el-input v-model="formData.coor" disabled></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="10">
          <el-form-item label="成立日期" prop="register_date">
            <el-date-picker type="date" placeholder="选择日期" v-model="formData.register_date"></el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="10">
          <el-form-item label="营业期限" prop="operating_date">
            <el-date-picker type="date" placeholder="选择日期" v-model="formData.operating_date"></el-date-picker>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="10">
          <el-form-item label="单位法人" prop="legal_person">
            <el-input v-model="formData.legal_person"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="10">
          <el-form-item label="联系电话" prop="legal_person_phone">
            <el-input v-model="formData.legal_person_phone"></el-input>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <el-col :span="10">
          <el-form-item label="经营状态" prop="manage_status">
            <el-select v-model="formData.manage_status" disabled placeholder="请选择">
              <el-option
                v-for="item in operateStatus"
                :key="item.id"
                :label="item.name"
                :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <form-option title="消防信息" style="margin-top: 20px;"></form-option>
      <el-row>
        <el-col :span="10">
          <el-form-item label="所属辖区" prop="enforceOrgIds">
            <el-cascader
              v-model="formData.enforceOrgIds"
              :props="orgProps"
              :disabled="disabledEdit"
              :options="orgOptions"
              @change="orgChanged">
            </el-cascader>
          </el-form-item>
        </el-col>
        <el-col :span="10">
          <el-form-item label="检查流程" prop="enforce_template_name">
            <el-input v-model="formData.enforce_template_name" suffix-icon="el-icon-arrow-down" placeholder="请选择"
                      @focus="showTemplate=true"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="10">
          <el-form-item label="单位规模" prop="enforce_obj_type">
            <el-select v-model="formData.enforce_obj_type" placeholder="请选择">
              <el-option
                v-for="item in unitSize"
                :key="item.id"
                :label="item.name"
                :value="item.id">
              </el-option>
              <el-option label="九小场所" value="5"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="10">
          <el-form-item label="场所类型" prop="place_type">
            <el-select v-model="formData.place_type" placeholder="请选择">
              <el-option
                v-for="item in placeType"
                :key="item.code"
                :label="item.name"
                :value="item.code">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="10">
          <el-form-item label="所在建筑" prop="architecture_type">
            <el-radio v-model="formData.architecture_type" label="1">高层建筑</el-radio>
            <el-radio v-model="formData.architecture_type" label="2">非高层建筑</el-radio>
          </el-form-item>
        </el-col>
        <el-col :span="10">
          <el-form-item label="消防安全" prop="hole_responsibility">
            <el-checkbox v-model="formData.hole_responsibility">负责整栋建筑消防安全</el-checkbox>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="10">
          <el-form-item label="面积" prop="area">
            <el-input v-model="formData.area"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="10">
          <el-form-item label="单位体量" prop="obj_mass">
            <el-input v-model="formData.obj_mass"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="10">
          <el-form-item label="消防安全责任人" prop="charge_person">
            <el-input v-model="formData.charge_person"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="10">
          <el-form-item label="联系电话" prop="charge_person_phone">
            <el-input v-model="formData.charge_person_phone"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="10">
          <el-form-item label="消防安全管理人" prop="manage_person">
            <el-input v-model="formData.manage_person"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="10">
          <el-form-item label="联系电话" prop="manage_person_phone">
            <el-input v-model="formData.manage_person_phone"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="10">
          <el-form-item label="联系人" prop="contact_person">
            <el-input v-model="formData.contact_person"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="10">
          <el-form-item label="联系电话" prop="contact_phone">
            <el-input v-model="formData.contact_phone"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <form-option title="安全合格证" style="margin-top: 20px;"></form-option>
      <el-row>
        <el-col :span="10">
          <el-form-item label="消防文件号数" prop="cer_no">
            <el-input v-model="formData.certificates.cer_no"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="10">
          <el-form-item label="使用性质" prop="usage_type">
            <el-input v-model="formData.certificates.usage_type"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="10">
          <el-form-item label="场所层数" prop="floor">
            <el-input v-model="formData.certificates.floor"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="20">
          <el-form-item label="消防设施" prop="facility">
            <el-input
              type="textarea"
              placeholder="请输入"
              :rows="3"
              v-model="formData.certificates.facility"
              maxlength="300"
              show-word-limit>
            </el-input>
            <!-- <el-input v-model="formData.certificates.facility" type="textarea" :rows="3" autosize></el-input> -->
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="15">
          <el-form-item label="证件上传" prop="file">
            <el-upload
              class="upload-demo"
              ref="upload"
              name="fileBinary"
              :headers="uploadHeaders"
              :data="uploadData"
              multiple
              with-credentials
              :action="fileUploadUrl"
              :on-remove="handleFileRemove"
              :on-success="handleFileSuccess"
              :on-preview="handlePictureCardPreview"
              :before-upload="beforeUploadFile"
              :file-list="fileList">
              <div class="file-upload">
                <el-button slot="trigger" size="small" icon="el-icon-upload" type="primary">上传文件</el-button>
                <div slot="tip" class="tip">支持文件格式：.jpeg .png .jpg ，单个文件不能超过500kb</div>
              </div>
            </el-upload>
            <!-- <div slot="tip" class="el-upload__tip">支持文件格式：.jpeg .png .jpg ，单个文件不能超过500kb</div> -->
          </el-form-item>
        </el-col>
      </el-row>
      <el-form-item>
        <el-button @click="handleCancel">取消</el-button>
        <el-button type="warning" @click="resetForm">重置</el-button>
        <el-button type="primary" @click="handleCommit">提交</el-button>
      </el-form-item>
    </el-form>
    <el-dialog :visible.sync="dialogVisible">
      <img width="100%" :src="dialogImageUrl" alt="">
    </el-dialog>
    <el-dialog title="选择单位地址" :visible.sync="showMap">
      <place-map v-if="showMap" ref="map" @changePlace="handlePlace" :address.sync="formData.enforce_obj_address" @hidePlace="showMap=false"></place-map>
    </el-dialog>
    <el-dialog title="选择流程" :visible.sync="showTemplate">
      <choose-template @changeTemplate="handleTemplate"></choose-template>
    </el-dialog>
  </div>
</template>

<script>
import FormOption from '@/component/FormOption.vue'
import PlaceMap from '@/component/PlaceMap.vue'
import ChooseTemplate from '@/component/ChooseTemplate.vue'

import { resourceMixin } from '@/mixin/resource'
import { fileMixin } from '@/mixin/fileMixin'
import { addEnforce, getEnforceItem, updateEnforce, getPlaceTypes } from '@/api/resource'
import { auth } from '@/utils/auth'
import request from '@/utils/request'
import { orgMixin } from '@/mixin/org';

export default {
  components: {
    FormOption,
    PlaceMap,
    ChooseTemplate
  },
  mixins: [resourceMixin, fileMixin, orgMixin],
  data () {
    return {
      loading: false,
      rightButton: {},
      formData: {
        imgUrl: '',
        name: null,
        enforce_obj_name: null,
        credit_code: '',
        enforce_obj_address: null,
        longitude: null,
        latitude: null,
        coor: null,
        register_date: null,
        operating_date: null,
        legal_person: null,
        legal_person_phone: null,
        enforceOrgIds: null,
        enforce_org: {
          enforce_org_id: null,
          enforce_org_name: null
        },
        enforce_template_id: null,
        enforce_template_name: null,
        enforce_obj_type: null,
        place_type: null,
        architecture_type: '1',
        hole_responsibility: false,
        area: null,
        obj_mass: null,
        charge_person: null,
        charge_person_phone: null,
        manage_person: null,
        manage_person_phone: null,
        contact_person: null,
        contact_phone: null,
        certificates: {
          cer_no: null,
          floor: null,
          facility: null,
          usage_type: null,
          file_ids: null
        },
        manage_status: null
      },
      rules: {
        enforce_obj_name: [
          { required: true, message: '请输入单位名称', trigger: 'blur' },
          { min: 1, max: 50, message: '长度在 1 到 50 个字符', trigger: 'blur' }
        ],
        credit_code: [
          { required: true, message: '请输入统一社会信用代码', trigger: 'blur' },
          { min: 18, max: 18, message: '18位字母加数字', trigger: 'blur' }
        ],
        enforce_obj_address: [
          { required: true, message: '请选择单位地址', trigger: 'change' },
        ],
        legal_person: [
          { required: true, message: '请输入单位法人', trigger: 'blur' },
          { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
        ],
        legal_person_phone: [
          { required: true, message: '请输入单位法人联系电话', trigger: 'blur' },
          { min: 11, max: 11, message: '请正确输入11位手机号码', trigger: 'blur' }
        ],
        manage_status: [
          { required: true, message: '请选择经营状态', trigger: 'change' },
        ],
        enforceOrgIds: [
          { required: true, message: '请选择所属辖区', trigger: 'change' },
        ],
        enforce_template_name: [
          { required: true, message: '请选择检查流程', trigger: 'change' },
        ],
        enforce_obj_type: [
          { required: true, message: '请选择单位规模', trigger: 'change' },
        ],
        place_type: [
          { required: true, message: '请选择场所类型', trigger: 'change' },
        ],
        architecture_type: [
          { required: true, message: '请选择所在建筑', trigger: 'change' },
        ],
        charge_person: [
          { required: true, message: '请输入消防安全责任人', trigger: 'blur' },
          { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
        ],
        charge_person_phone: [
          { required: true, message: '请输入消防安全责任人联系电话', trigger: 'blur' },
          { min: 11, max: 11, message: '请正确输入11位手机号码', trigger: 'blur' }
        ],
        manage_person: [
          { required: true, message: '请输入消防安全管理人', trigger: 'blur' },
          { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
        ],
        manage_person_phone: [
          { required: true, message: '请输入消防安全管理人联系电话', trigger: 'blur' },
          { min: 11, max: 11, message: '请正确输入11位手机号码', trigger: 'blur' }
        ],
        contact_person: [
          { required: true, message: '请输入联系人', trigger: 'blur' },
          { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
        ],
        contact_phone: [
          { required: true, message: '请输入联系人联系电话', trigger: 'blur' },
          { min: 11, max: 11, message: '请正确输入11位手机号码', trigger: 'blur' }
        ],
        obj_mass: [
          { min: 1, max: 50, message: '长度在 1 到 50 个字符', trigger: 'blur' }
        ],
        cer_no: [
          { min: 1, max: 50, message: '长度在 1 到 100 个字符', trigger: 'blur' }
        ],
        usage_type: [
          { min: 1, max: 50, message: '长度在 1 到 100 个字符', trigger: 'blur' }
        ],
        floor: [
          { min: 1, max: 50, message: '长度在 1 到 10 个字符', trigger: 'blur' }
        ],
        facility: [
          { min: 1, max: 50, message: '长度在 1 到 100 个字符', trigger: 'blur' }
        ],
      },
      showMap: false,
      showTemplate: false,
      fileList: [],
      uploadData: {
        fileName: ''
      },
      uploadHeaders: {
        token: auth.getToken()
      },
      dialogImageUrl: '',
      dialogVisible: false,
      disabledEdit: true
    }
  },
  computed: {
    resourceId () {
      return this.$route.query.id
    },
    user () {
      return auth.getUserInfo() || {}
    }
  },
  mounted () {
    this.loading = true;
    this.loadOrgTree();
    this.getPlaceTypeData();
    this.getResourceDetail()
    // 55c99876ec0f425aac6925a92cceeb17  总队和admin
    this.disabledEdit = !(this.user.enforce_org_id === '55c99876ec0f425aac6925a92cceeb17' || this.user.account === 'admin')
  },
  methods: {
    getResourceDetail () {
      if (this.resourceId) {
        getEnforceItem(this.resourceId).then((res) => {
          if (!res.enforce_org) {
            res.enforce_org = {
              enforce_org_id: res.enforce_org_id
            }
          }
          res.hole_responsibility = res.hole_responsibility === 1
          res.coor = `${res.longitude},${res.latitude}`
          res.certificates = res.certificates[0] || {}
          res.manage_status = this.manageStatus[res.manage_status] || ''
          // this.initEnforceOrgs(res)
          res.enforceOrgIds = res.enforce_org_id
          this.formData = res
          if (this.formData.certificates.file_ids) {
            this.getFile(this.formData.certificates.file_ids)
          }

          this.loading = false;
        })
      }
      else {
        this.loading = false;
      }
    },
    getPlaceTypeData() {
      getPlaceTypes().then(result => {
        this.placeType = result;
        this.getResourceDetail();
      });
    },
    openMap(address) {
      this.addressTitle = address
      this.addressMap = true
      this.$nextTick(() => {
        // eslint-disable-next-line no-undef
        const map = new AMap.Map('container', {
          resizeEnable: true,
          animateEnable: true,
          zoom: 16
        })
        // eslint-disable-next-line no-undef
        this.marker = new AMap.Marker({
          map: map,
          icon: 'https://webapi.amap.com/theme/v1.3/markers/n/mark_b.png',
        })
        // eslint-disable-next-line no-undef
        AMap.plugin('AMap.PlaceSearch', () => {
          // eslint-disable-next-line no-undef
          let placeSearch = new AMap.PlaceSearch({
            pageSize: 1, // 单页显示结果条数
            pageIndex: 1, // 页码
            extensions: 'all',
          })
          placeSearch.search(address, (status, result) => {
            if (status === 'complete' && result.poiList.pois && result.poiList.pois.length > 0) {
              let l = result.poiList.pois[0].location
              // eslint-disable-next-line no-undef
              this.marker.setPosition(new AMap.LngLat(l.lng, l.lat))
              // eslint-disable-next-line no-undef
              map.setCenter(new AMap.LngLat(l.lng, l.lat))
            }
          })
        })
      })
    },
    getOrgParent (list, orgId) {
      for (let i in list) {
        if (list[i].orgId === orgId) {
          return [list[i]]
        }
        if (list[i].children) {
          let node = this.getOrgParent(list[i].children, orgId)
          if (node !== undefined) {
            return node.concat(list[i])
          }
        }
      }
    },
    initEnforceOrgs (res) {
      if (this.orgOptions && this.orgOptions.length > 0) {
        const nodes = this.getOrgParent(this.orgOptions, res.enforce_org_id)
        if (nodes && nodes.length > 0) {
          const list = new Array()
          nodes.map(item => {
            list.push(item.orgId)
          })
          list.reverse()
          res.enforceOrgIds = list
        }
      }
    },
    getFile (fileIds) {
      let fileList = fileIds.split(',')
      fileList.forEach(fileId => {
        request.get(`/v2/api/file/${fileId}`, {
          responseType: 'blob',
        }).then(res => {
          let blob = new Blob([res])
          this.fileList.push({
            response:{
              id: fileId,
            },
            url: window.URL.createObjectURL(blob)
          })
        })
      })
    },
    orgChanged (data) {
      if (!data) {
        return
      }
      let list = this.orgOptions
      for (let index = 0; index < data.length; index++) {
        const item = data[index]
        const res = list.filter(obj => item === obj.orgId)
        if (res.length > 0) {
          if (index < data.length - 1) {
            list = res[0].children
            continue
          } else {
            this.formData.enforce_org.enforce_org_id = res[0].orgId
            this.formData.enforce_org.enforce_org_name = res[0].orgName
            this.formData.enforce_org_id = res[0].orgId
            break
          }
        }
      }
    },
    handlePlace (data) {
      if (data) {
        this.formData.enforce_obj_address = data.address
        this.formData.longitude = data.lon
        this.formData.latitude = data.lat
        this.formData.coor = `${data.lon},${data.lat}`
      }
      this.showMap = false
    },
    changeCreditCode () {
      if (this.formData.credit_code) {
        this.formData.credit_code = this.formData.credit_code.toUpperCase()
      }
    },
    handleTemplate (data) {
      this.formData.enforce_template_id = data.id
      this.formData.enforce_template_name = data.template_name
      this.showTemplate = false
    },
    beforeUploadFile (file) {
      if (!/^image\/(jpeg|png|jpg)$/.test(file.type)) {
        this.$message.warning(`上传图片格式不对[${file.name}]`)
        return false
      }
      if (file.size > 512000) {
        this.$message.warning(`文件大小不能超过500kb[${file.name}]`)
        return false
      }
      this.uploadData.fileName = file.name
      return true
    },
    handleRemove (file, fileList) {
      this.handleUploadFiles(fileList)
    },
    handlePictureCardPreview (file) {
      this.dialogImageUrl = file.url
      this.dialogVisible = true
    },
    handleFileRemove (file, fileList) {
      this.handleUploadFiles(fileList)
    },
    handleFileSuccess (res, file, fileList) {
      this.handleUploadFiles(fileList)
    },
    handleUploadFiles (fileList) {
      const res = []
      fileList.map(item => {
        if (item.response && item.response.id) {
          res.push(item.response.id)
        }
      })
      this.formData.certificates.file_ids = res.join(',')
    },
    handleCancel () {
        this.loading = false;
        this.$router.back()
    },
    handleCommit () {
      const vm = this
      this.$refs['ruleForm'].validate((valid) => {
        if (valid) {
          const info = Object.assign({}, this.formData)
          let have = false;
          if (info.certificates && info.certificates.length > 0) {
            for (let index = 0; index < info.certificates.length; index++) {
              const cer = info.certificates[index];
              if (cer.cer_no && cer.cer_no.length > 100) {
                have = true;
                vm.$message.error('消防文件号数不能超过100字符');
                break;
              }
              if (cer.usage_type && cer.usage_type.length > 100) {
                have = true;
                vm.$message.error('使用性质不能超过100字符');
                break;
              }
              if (cer.facility && cer.facility.length > 100) {
                have = true;
                vm.$message.error('消防设施不能超过100字符');
                break;
              }
            }
          }
          if (have) {
            return false;
          }
          info.hole_responsibility = this.formData.hole_responsibility ? 1 : 0
          info.certificates = [this.formData.certificates]
          if (info.manage_status == '正常') info.manage_status = 0
          if (info.manage_status == '冻结') info.manage_status = 1
          if (info.manage_status == '注销') info.manage_status = 2
          this.loading = true;
          info.hole_responsibility = this.formData.hole_responsibility ? 1 : 0;
          info.certificates = [this.formData.certificates];
          if (vm.formData.id) {
            updateEnforce(vm.formData.id, info).then(() => {
              vm.$message.success('修改成功')
              vm.handleCancel()
            }).catch(e => {
                this.loading = false;
            });
          } else {
            addEnforce(info).then(() => {
              vm.$message.success('新增成功')
              vm.handleCancel()
            }).catch(e => {
                this.loading = false;
            });
          }
        }
      })
    },
    resetForm () {
      this.$refs['ruleForm'].resetFields()
      this.formData.certificates.cer_no = ''
      this.formData.certificates.usage_type = ''
      this.formData.certificates.floor = ''
      this.formData.certificates.facility = ''
      this.fileList = []
    }
  }
}
</script>

<style lang="scss" scoped>
.info {
  display: flex;
  flex-direction: column;
  padding: 16px 16px 0;
  background-color: #FFFFFF;
  border-radius: 10px;
}
.file-upload {
  display: flex;
  align-items: center;
  .tip {
    margin-left: 14px;
    font-size: 12px;
    color: #606266;
  }
}
</style>
