<template>
  <a-modal
    :title="$t('机构信息')"
    :visible="visible"
    :destroy-on-close="true"
    width="70%"
    @ok="submit"
    @cancel="visible = false"
    :ok-text="$t('保存')"
    :cancel-text="$t('取消')"
  >
    <a-form-model
      ref="editForm"
      :model="editForm"
      :rules="rules"
      :label-col="{ span: 9 }"
      :wrapper-col="{ span: 15 }"
    >
      <a-row :gutter="12">
        <a-col :span="16">
          <a-row :gutter="12">
            <a-col :span="12">
              <a-form-model-item
                :label="$t('机构名称')"
                prop="orgName"
              >
                <a-input
                  v-model="editForm.orgName"
                  :placeholder="$t('请输入机构名称')"
                  :maxLength="50"
                />
              </a-form-model-item>
            </a-col>
            <a-col :span="12">
              <a-form-model-item
                :label="$t('上级机构')"
                prop="parentOrg"
              >
                <a-select
                  v-model="editForm.parentOrg"
                  :placeholder="$t('请选择机构，空为高级')"
                  :options="orgList"
                  :disabled="editForm.parentOrg == 0"
                >
                </a-select>
              </a-form-model-item>
            </a-col>
          </a-row>
          <a-row>
            <a-col :span="12">
              <a-form-model-item
                :label="$t('系统机构代码')"
                prop="sysOrgCode"
              >
                <a-input
                  v-model="editForm.sysOrgCode"
                  :placeholder="$t('请输入系统机构代码')"
                />
              </a-form-model-item>
            </a-col>
            <a-col :span="12">
              <a-form-model-item
                :label="$t('组织机构代码')"
                prop="orgCode"
              >
                <a-input
                  v-model="editForm.orgCode"
                  :placeholder="$t('请输入组织机构代码')"
                />
              </a-form-model-item>
            </a-col>
          </a-row>
          <a-row>
            <a-col :span="12">
              <a-form-model-item
                :label="$t('机构类别')"
                prop="orgType"
              >
                <a-select
                  v-model="editForm.orgType"
                  :placeholder="$t('请选择机构类别')"
                  :options="orgTypeList"
                >
                </a-select>
              </a-form-model-item>
            </a-col>
            <a-col :span="12">
              <a-form-model-item
                :label="$t('机构简称')"
                prop="alias"
              >
                <a-input
                  v-model="editForm.alias"
                  :placeholder="$t('请输入机构简称')"
                />
              </a-form-model-item>
            </a-col>
          </a-row>
          <a-row>
            <a-col :span="12">
              <a-form-model-item
                :label="$t('医院级别')"
                prop="hospitalLevel"
              >
                <a-select
                  v-model="editForm.hospitalLevel"
                  :placeholder="$t('请选择医院级别')"
                  :options="hospLevelList"
                >
                </a-select>
              </a-form-model-item>
            </a-col>
            <a-col :span="12">
              <a-form-model-item
                :label="$t('机构状态')"
                prop="isEnable"
              >
                <a-switch v-model="editForm.isEnable"></a-switch>
              </a-form-model-item>
            </a-col>
          </a-row>
        </a-col>
        <a-col
          :span="8"
          align="center"
        >
          <a-form-model-item
            :label-col="{ span: 0 }"
            :wrapper-col="{ span: 24 }"
            prop="orgLogo"
          >
            <div class="institution_avatar_uploader">
              <img
                class="org_logo"
                :src="defaultimg"
                alt="avatar"
              />
            </div>
            <a-upload
              v-if="false"
              name="file"
              class="institution_avatar_uploader"
              :show-upload-list="false"
              @change="uploadFun"
              :headers="{
                Authorization: `${$storage.get('tokey')}@${$storage.get('Bearer')}`,
              }"
              accept="image/png, image/jpeg, image/gif, image/jpg"
              :action="action"
              :beforeUpload="beforeUpload"
            >
              <img
                class="org_logo"
                :src="defaultimg"
                alt="avatar"
              />
              <div class="upload_icon">
                <span>{{ $t('浏览') }}</span>
              </div>
            </a-upload>
          </a-form-model-item>
        </a-col>
      </a-row>
      <a-row :gutter="12">
        <a-col :span="8">
          <a-form-model-item
            :label="$t('联系电话')"
            prop="telphone"
          >
            <a-input
              v-model="editForm.telphone"
              :placeholder="$t('请输入联系电话')"
              :maxLength="12"
            />
          </a-form-model-item>
        </a-col>
        <a-col :span="8">
          <a-form-model-item
            :label="$t('传真')"
            prop="fax"
          >
            <a-input
              v-model="editForm.fax"
              :placeholder="$t('请输入传真')"
              :maxLength="16"
            />
          </a-form-model-item>
        </a-col>
        <a-col :span="8">
          <a-form-model-item
            :label="$t('邮编')"
            prop="postcode"
          >
            <a-input
              v-model="editForm.postcode"
              :placeholder="$t('请输入邮编')"
              :maxLength="6"
            />
          </a-form-model-item>
        </a-col>
      </a-row>
      <a-row>
        <a-col :span="24">
          <a-form-model-item
            :label-col="{ span: 3 }"
            :wrapper-col="{ span: 21 }"
            :label="$t('详细地址')"
            jprop="address"
          >
            <a-textarea
              :rows="5"
              v-model="editForm.address"
              :placeholder="$t('请输入详细地址')"
              :maxLength="200"
            />
          </a-form-model-item>
        </a-col>
      </a-row>
    </a-form-model>
  </a-modal>
</template>
<script>
  const default_orgLogo = require('w-vue-basis/src/assets/images/default_orgLogo.jpg'); //默认机构介绍图
  const $appService = require('w-vue-basis/src/api/appService');

  export default {
    computed: {
      visible: {
        get() {
          return this.show;
        },
        set(val) {
          this.$emit('update:show', val);
        },
      },
    },
    props: {
      show: [Boolean],
      info: [Object],
    },
    watch: {
      show(val) {
        if (val) {
          this.editForm = {
            ...this.info,
            isEnable: this.info.isEnable == 1 ? false : true,
          };
          if (this.editForm.orgLogo) {
            // this.defaultimg = `${this.editForm.orgLogo}`;
          }
          this.getOrgList();
          this.getSysDictData('org_type');
          this.getSysDictData('hospital_level');
        }
      },
    },
    data() {
      return {
        action: `${$service.portalService}/common/upload`,
        defaultimg: `${default_orgLogo}`,
        orgList: [],
        orgTypeList: [],
        hospLevelList: [],
        editForm: {
          orgId: undefined,
          orgName: undefined,
          parentOrg: undefined,
          sysOrgCode: undefined,
          orgCode: undefined,
          orgType: undefined,
          alias: undefined,
          hospitalLevel: undefined,
          isEnable: undefined,
          orgLogo: undefined,
          telphone: undefined,
          fax: undefined,
          postcode: undefined,
          address: undefined,
        },
        rules: {
          orgName: [{ required: true, message: $t('请输入机构名称'), trigger: 'blur' }],

          orgType: [{ required: true, message: $t('请选择机构类别'), trigger: 'change' }],

          hospitalLevel: [{ required: true, message: $t('请选择医院级别'), trigger: 'change' }],

          sysOrgCode: [{ required: true, message: $t('请输入系统机构代码'), trigger: 'change' }],

          orgCode: [{ required: true, message: $t('请输入组织代码'), trigger: 'change' }],

          telphone: [
            {
              validator: (rule, value, callback) => {
                let masage = '';
                var reg =
                  /^1((34[0-8])|(8\d{2})|(([35][0-35-9]|4[579]|66|7[35678]|9[13589])\d{1}))\d{7}$/;
                if (!value) {
                  callback();
                } else if (!reg.test(value)) {
                  masage = $t('手机号码格式不正确');
                  return callback(new Error(`${masage}!`));
                } else {
                  callback();
                }
              },
              trigger: 'blur',
            },
          ],
        },
      };
    },
    created() {},
    methods: {
      /**
       * @Author: y_zp
       * @description: 保存
       */
      submit() {
        this.$refs.editForm.validate((valid) => {
          if (valid) {
            let {
              orgName,
              parentOrg,
              sysOrgCode,
              orgCode,
              orgType,
              alias,
              hospitalLevel,
              orgLogo,
              telphone,
              fax,
              postcode,
              address,
            } = { ...this.editForm };
            let orgId = this.editForm.orgId || undefined;
            let isEnable = this.editForm.isEnable ? 0 : 1;
            $appService
              .sysOrgSave({
                orgId,
                orgName,
                parentOrg: parentOrg || 0,
                sysOrgCode,
                orgCode,
                orgType,
                alias,
                hospitalLevel,
                isEnable,
                orgLogo,
                telphone,
                fax,
                postcode,
                address,
              })
              .then((res) => {
                this.visible = false;
                this.$message.success(`${this.info.orgId ? $t('编辑') : $t('新增')}${$t('成功')}`);
                this.$emit('callBack');
              });
          }
        });
      },

      /**
       * @Author: y_zp
       * @description: 获取机构
       */
      getOrgList() {
        $appService.getSysOrg({ pageNum: 1, pageSize: 1000000 }).then((req) => {
          this.orgList = req.data.map((item) => {
            return {
              label: item.orgName,
              value: item.orgId,
            };
          });
          this.orgList.unshift({
            value: '0',
            label: $t('最高级'),
          });
        });
      },

      /**
       * @Author: y_zp
       * @description: 获取字典
       */
      getSysDictData(type) {
        $appService
          .getSysDictData({
            pageNum: 1,
            pageSize: 1000000,
            queryParams: { F_dictType_eq: type },
          })
          .then((req) => {
            let info = req.data.map((item) => {
              return {
                label: $t(item.dictLabel),
                value: item.dictValue,
              };
            });
            type == 'org_type' && (this.orgTypeList = info);
            type == 'hospital_level' && (this.hospLevelList = info);
          });
      },
      beforeUpload(file, fileList) {
        let type = file.type;
        if (['image/png', 'image/jpg', 'image/jpeg', 'image/gif'].indexOf(type) == -1) {
          this.$message.warn($t('请选择图片'));
          return false;
        }
      },
      /**
       * @Author: y_zp
       * @description: 上传
       */
      uploadFun(info) {
        if (info.file.status === 'done') {
          if (info.file.response.success) {
            this.editForm.orgLogo = info.file.response.data.fileName;
            this.defaultimg = `${this.editForm.orgLogo}?time=${new Date().getTime()}`;
          } else {
            this.$message.error(info.file.response.errorDetail);
          }
        } else if (info.file.status === 'error') {
          this.$message.error($t('上传失败，请重试'));
        }
      },
    },
  };
</script>
<style lang="less" scoped>
  .institution_avatar_uploader {
    position: relative;
    cursor: pointer;
    display: block;
    width: 100%;
    height: 100%;
    .org_logo {
      height: 180px;
    }
    .upload_icon {
      position: absolute;
      left: 0;
      bottom: 0;
      color: #fff;
      background: rgba(0, 0, 0, 0.5);
      right: 0;
      height: 30px;
      line-height: 30px;
    }
  }
</style>
