<template>
  <div>
    <!-- form -->
    <a-form-model ref="form" layout="vertical" :model="form" :rules="formRules">
      <a-row :gutter="30">
        <a-col :xl="6" :lg="6" :sm="12">
          <a-form-model-item label="病历号码" prop="mrnNo">
            <a-input v-model="form.mrnNo" placeholder="请输入病历号" allow-clear></a-input>
          </a-form-model-item>
          <a-form-model-item label="证件号码" prop="idNo">
            <a-input v-model="form.idNo" allow-clear placeholder="请输入证件号码"></a-input>
          </a-form-model-item>
          <a-form-model-item label="保单号码" prop="policyNo">
            <a-input allow-clear v-model="form.policyNo" placeholder="请输入保单号码"></a-input>
          </a-form-model-item>
          <a-form-model-item label="保单直付区域" prop="policyDircetArea">
            <a-select v-model="form.policyDircetArea" placeholder="请选择保单直付区域" show-search allow-clear :filterOption="filterCode">
              <a-select-option v-for="item in areaCode" :key="item.refcd" :value="item.refcd" :label="item.descCh">{{ item.descCh }}</a-select-option>
            </a-select>
          </a-form-model-item>
        </a-col>
        <a-col :xl="4" :lg="6" :sm="12">
          <a-form-model-item label="客户姓名" prop="patientName">
            <a-input v-model="form.patientName" allow-clear placeholder="请输入客户姓名"></a-input>
          </a-form-model-item>
          <a-form-model-item label="保险公司" prop="payorId">
            <a-select v-model="form.payorId" placeholder="请选择保险公司" show-search allow-clear :filterOption="filterCode" @change="payorChange">
              <a-select-option v-for="item in companyCode" :key="item.id" :value="item.id" :label="item.longName">{{ item.longName }}</a-select-option>
            </a-select>
          </a-form-model-item>
          <a-form-model-item label="首次入保时间" prop="firstEnrollmentTime">
            <a-date-picker allow-clear v-model="form.firstEnrollmentTime" placeholder="请选择首次入保时间" value-format="YYYY-MM-DD 00:00:00"></a-date-picker>
          </a-form-model-item>
          <a-form-model-item label="等待期" prop="waitingPeriod">
            <a-radio-group v-model="form.waitingPeriod" :default-value="form.waitingPeriod" button-style="solid">
              <a-radio-button value="Y"> 是 </a-radio-button>
              <a-radio-button class="mar-left10" value="N"> 否 </a-radio-button>
            </a-radio-group>
          </a-form-model-item>
        </a-col>
        <a-col :xl="4" :lg="6" :sm="12">
          <a-form-model-item label="出生日期" prop="birthday">
            <a-date-picker v-model="form.birthday" allow-clear placeholder="请选择出生日期" value-format="YYYY-MM-DD 00:00:00"></a-date-picker>
          </a-form-model-item>
          <a-form-model-item label="客户公司名称" prop="corpName">
            <a-select v-model="form.corpName" placeholder="请选择客户公司名称" show-search allow-clear
              :filterOption="filterCode" @change="corpChange" @search="corpSearch">
              <a-select-option v-for="item in comCorpCode" :key="item.id" :value="item.id + '$_' + item.longName">
                {{ item.longName }}
              </a-select-option>
            </a-select>
          </a-form-model-item>
          <a-form-model-item label="保单生效日期" prop="startDate">
            <a-date-picker allow-clear v-model="form.startDate" placeholder="请选择保单生效日期" value-format="YYYY-MM-DD 00:00:00"></a-date-picker>
          </a-form-model-item>
          <a-form-model-item label="是否承担既往症" prop="isUndertakeAnamnesis">
            <a-radio-group v-model="form.isUndertakeAnamnesis" :default-value="form.isUndertakeAnamnesis" button-style="solid">
              <a-radio-button value="Y"> 是 </a-radio-button>
              <a-radio-button class="mar-left10" value="N"> 否 </a-radio-button>
            </a-radio-group>
          </a-form-model-item>
        </a-col>
        <a-col :xl="4" :lg="6" :sm="12">
          <a-form-model-item label="性别" prop="sex">
            <a-radio-group v-model="form.sex" :default-value="form.sex" button-style="solid">
              <a-radio-button value="M"> 男 </a-radio-button>
              <a-radio-button class="mar-left10" value="F"> 女 </a-radio-button>
            </a-radio-group>
          </a-form-model-item>
        </a-col>
        <a-col :xl="6" :lg="6" :sm="12">
          <a-form-model-item label="证件类型" prop="idType">
            <a-select v-model="form.idType" placeholder="请选择证件类型" show-search allow-clear :filterOption="filterCode">
              <a-select-option v-for="item in typeCode" :key="item.refcd" :value="item.refcd" :label="item.descCh">{{ item.descCh }}</a-select-option>
            </a-select>
          </a-form-model-item>
        </a-col>
        <a-col :xl="6" :lg="6" :sm="12">
          <a-form-model-item label="保险卡号" prop="cardNo">
            <a-input allow-clear v-model="form.cardNo" placeholder="请输入保险卡号"></a-input>
          </a-form-model-item>
        </a-col>
        <a-col :xl="5" :lg="6" :sm="12">
          <a-form-model-item label="保单终止日期" prop="endDate">
            <a-date-picker allow-clear v-model="form.endDate" placeholder="请选择保单终止日期" value-format="YYYY-MM-DD 00:00:00"></a-date-picker>
          </a-form-model-item>
        </a-col>
        <a-col :xl="6" :lg="6" :sm="12">
          <a-form-model-item label="保险计划" prop="planName">
            <a-select v-model="form.planName" placeholder="请选择保险计划" show-search allow-clear :filterOption="filterCode" @search="codeSearch"
            >
              <a-select-option v-for="item in comPlanCode" :key="item.id + '_' + item.longName" :value="item.longName">
                {{ item.longName }}
              </a-select-option>
            </a-select>
          </a-form-model-item>
        </a-col>
        <a-col :xl="6" :lg="6" :sm="12">
          <a-form-model-item label="其他备注" prop="remark">
            <a-input allow-clear v-model="form.remark" placeholder="请输入备注信息"></a-input>
          </a-form-model-item>
        </a-col>
      </a-row>
      <a-row :gutter="10">
        <a-col :xl="9" :sm="12" class="none-label">
          <a-form-model-item label="" prop="medCardCopeFiles">
            <div class="text-left mar-bottom10">
              <label>保卡复印件</label>
              <a-button type="primary" size="small" class="mar-left10" ghost>打印</a-button>
            </div>
            <div class="upload-print">
              <div class="picture">
                <a-upload
                  action=""
                  accept="image/*"
                  list-type="picture-card"
                  :file-list="medCardCopeFiles"
                  :beforeUpload="uploadMedImg"
                  @preview="handlePreview"
                  :remove="handleMedRemove"
                >
                  <div v-if="form.medCardCopeFiles.length < 3">
                    点击上传文件
                  </div>
                </a-upload>
              </div>
              <!-- <a-button type="primary" class="mar-left10" ghost>打印</a-button> -->
            </div>
          </a-form-model-item>
        </a-col>
        <a-col :xl="9" :sm="12" class="none-label">
          <a-form-model-item prop="idCardCopeFiles">
            <div class="text-left mar-bottom10">
              <label>身份证复印件</label>
              <a-button type="primary" size="small" class="mar-left10" ghost>打印</a-button>
            </div>
            <div class="upload-print">
              <div class="picture">
                <a-upload
                  action=""
                  list-type="picture-card"
                  :beforeUpload="uploadIDImg"
                  :file-list="idCardCopeFiles"
                  @preview="handlePreview"
                  :remove="handleIDRemove"
                >
                  <div v-if="form.idCardCopeFiles.length < 3">点击上传文件</div>
                </a-upload>
              </div>
            </div>
          </a-form-model-item>
        </a-col>
      </a-row>
      <a-row>
        <a-col :xl="24" :lg="18" :sm="12" class="none-label clearfix">
          <a-form-model-item label="button">
            <!-- <a-button type="primary">
              <Icon name="ssiprint" :size="14" />打印理赔申请书
            </a-button> -->
            <a-button class="mar-left10 text-r" type="primary" @click="handlerSave">
              <Icon name="ssidownload" :size="14" />保存
            </a-button>
            <a-button type="primary" class="mar-left10 text-r" @click="handlerReset">
              <Icon name="ssireset" :size="14" />重置
            </a-button>
          </a-form-model-item>
        </a-col>
      </a-row>
    </a-form-model>
    <a-modal :visible="previewVisible" :footer="null" @cancel="handleClose">
      <img alt="example" style="width: 100%" :src="previewImage" />
    </a-modal>
  </div>
</template>

<script>
export default {
  beforeRouteUpdate(to, from, next) {
    this.$refs.form.resetFields();
    next();
  },
  data() {
    return {
      previewVisible: false,
      form: {
        sex: 'U',
        payorId: undefined,
        corpName: undefined,
        planName: undefined,
        waitingPeriod: "N",
        isUndertakeAnamnesis: "N",
        medCardCopeFiles: [],
        idCardCopeFiles: [], // 身份证复印件
      },
      medCardCopeFiles: [],
      idCardCopeFiles: [], // 身份证复印件
      previewImage: "",
      companyCode: [],
      corpCode: [],
      comCorpCode: [],
      planCode: [],
      comPlanCode: [],
      formRules: {
        mrnNo: [{required: true, message: '请输入病历号'}],
        patientName: [{required: true, message: '请输入客户姓名'}],
        birthday: [{required: true, message: '请选择出生日期'}],
        sex: [{required: true, message: '请选择性别'}],
        payorId: [{required: true, message: '请选择保险公司'}],
        cardNo: [{required: true, message: '请输入保险卡号'}],
      },
      typeCode: [],
      areaCode: []
    };
  },
  mounted() {
    if (this.$route.query && this.$route.query.id) {
      this.getCustomerDetail(this.$route.query);
    }
    this._getPayorCode();
    this.initCodeData();
  },
  methods: {
    handlerSave() {
      this.$refs.form.validate((valid) => {
        if (!valid) {
          return false;
        }
        const fn = this.form.id || this.form.id === 0 ? this.$apis.UPDATECUSTOMDATA : this.$apis.CREATENEWCUSTOMER
        fn(this.form).then((res) => {
          if (res.returnCode === "0000") {
            this.$message.success("操作成功");
            const { id, patientPolicyId } = res.content || {};
            this.$router.push({
              name: "welfareInfo",
              query: { id: id || this.form.id, patientPolicyId: patientPolicyId || this.form.patientPolicyId },
            });
            // this.$router.push("/customer");
          } else {
            this.$message.error(res.returnMsg || "操作失败");
          }
        });
      });
    },
    handlerReset() {
      this.$refs.form.resetFields();
      this.form.medCardCopeFiles = [];
      this.medCardCopeFiles = [];
      this.form.idCardCopeFiles = [];
      this.idCardCopeFiles = [];
    },
    payorChange(val) {
      this.form.corpName = undefined;
      if (!val) {
        return false;
      }
      this._getCorporateCode(val);
    },
    corpSearch(val) {
      if (!val) {
        this.comCorpCode = this.corpCode;
        return;
      }
      let noOne = this.corpCode.every((item) => {
        return item.longName.indexOf(val) == -1;
      });
      if (noOne) {
        this.comCorpCode = [
          ...this.corpCode,
          {
            longName: val,
            id: "",
          },
        ];
      }
    },
    getCustomerDetail(params) {
      // this.queryForm = this.$lodash.cloneDeep(this.form);
      const { id, patientPolicyId, type } = params;
      const data = {
        id: id && id * 1,
        patientPolicyId: patientPolicyId * 1,
      };
      this.$apis.GETCUSTOMERDETAIL(data).then((res) => {
        if (res.returnCode === "0000") {
          let data = res.content || {};
          this._getCorporateCode(data.payorId);
          this._getPlanCode(data.corpId);
          const medCardCopeFiles = data.medCardCopeFiles || [];
          const idCardCopeFiles = data.idCardCopeFiles || [];
          medCardCopeFiles.forEach((item) => {
            this.medCardCopeFiles.push({
              url: item.fileUrl,
              uid: item.fileUrl,
              name: item.fileName,
            })
          })
          idCardCopeFiles.forEach((item) => {
            this.idCardCopeFiles.push({
              url: item.fileUrl,
              uid: item.fileUrl,
              name: item.fileName,
            })
          })
          // type === '2'说明是新增保单,需要把客户信息清空
          if(type === '2') {
            data = {
              ...data,
              payorId: undefined,
              corpName: '',
              idType: undefined,
              policyNo: '',
              firstEnrollmentTime: '',
              startDate: '',
              cardNo: '',
              policyDircetArea: undefined,
              waitingPeriod: 'N',
              isUndertakeAnamnesis: "N",
              endDate: '',
              planName: undefined,
              remark: '',
              medCardCopeFiles: [],
              idCardCopeFiles: [], // 身份证复印件
            }
            this.medCardCopeFiles = [];
            this.idCardCopeFiles = [];
          }
          this.form = data;
        }
        // this.dataList = (res.content && res.content.list) || [];
        // this.total = (res.content && res.content.total) || 0;
      });
    },
    codeSearch(val) {
      if (!val) {
        this.comPlanCode = this.planCode;
        return;
      }
      let noOne = this.planCode.every((item) => {
        return item.longName.indexOf(val) == -1;
      });
      if (noOne) {
        this.comPlanCode = [
          ...this.planCode,
          {
            longName: val,
            id: "",
          },
        ];
      }
    },
    corpChange(val) {
      // 因为接口要name  但是查计划要用id
      this.form.planName = undefined;
      if (!val) {
        return false;
      }
      this.form.corpName = val.split("$_")[1];
      val = val.split("$_")[0];
      if (val) {
        this._getPlanCode(val);
      } else {
        this.planCode = [];
        this.comPlanCode = [];
      }
    },
    uploadMedImg(file) {
      console.log(file);
      // this.form.medCardCopeFiles.push(file);
      this.uploadFile(file, "1");
      return false;
    },
    uploadIDImg(file) {
      this.uploadFile(file, "2");
      return false;
    },
    uploadFile(file, type) {
      let formData = new FormData();
      formData.append("file", file);
      this.$apis.UPLOADIMG(formData).then((res) => {
        if (res.state === "SUCCESS") {
          const { original, title, url } = res;
          let fileItem = {
            fileName: title,
            fileType: type,
            fileUrl: url,
          };
          let showItem = {
            url,
            uid: url,
            name: original,
          };
          if (type === "1") {
            this.form.medCardCopeFiles.push(fileItem);
            this.medCardCopeFiles.push(showItem);
          } else {
            this.form.idCardCopeFiles.push(fileItem);
            this.idCardCopeFiles.push(showItem);
          }
        }
      });
      return false;
    },
    handleMedRemove(file) {
      for (let i = 0; i < this.medCardCopeFiles.length; i++) {
        if (this.medCardCopeFiles[i].url === file.url) {
          this.medCardCopeFiles.splice(i, 1);
          this.form.medCardCopeFiles.splice(i, 1);
          return true;
        }
      }
    },
    handleIDRemove(file) {
      for (let i = 0; i < this.idCardCopeFiles.length; i++) {
        if (this.idCardCopeFiles[i].url === file.url) {
          this.idCardCopeFiles.splice(i, 1);
          this.form.idCardCopeFiles.splice(i, 1);
          return true;
        }
      }
    },
    handlePreview(file) {
      this.previewImage = file.url;
      this.previewVisible = true;
    },
    handleClose() {
      this.previewVisible = false;
    },
    initCodeData() {
      const params = {
        typeCode: {
          modid: "CI",
          refgrp: "ID_TYPE"
        },
        areaCode: {
          modid: "CI",
          refgrp: "POLICY_DIRECT_AREA"
        },
      }
      for (let i in params) {
        this._getRefcdByRefgrp(params[i], i)
      }
    },
    // 选择框筛选
    filterCode(input, option) {
      return (
        option.componentOptions.children[0].text
          .toLowerCase()
          .indexOf(input.toLowerCase()) >= 0
      );
    },
    _getPayorCode() {
      this.$apis.GETPAYORCODE({}).then((res) => {
        this.companyCode = res.content || [];
      });
    },
    _getCorporateCode(val) {
      this.$apis
        .GETCORPORATECODEBYPAYOR({
          longName: "",
          payorId: val,
        })
        .then((res) => {
          this.corpCode = res.content || [];
          this.comCorpCode = res.content || [];
        });
    },
    _getPlanCode(val) {
      this.$apis
        .GETPLANCODEBYCORP({
          longName: "",
          corpId: val,
        })
        .then((res) => {
          this.planCode = res.content || [];
          this.comPlanCode = res.content || [];
        });
    },
    _getRefcdByRefgrp(data, prop) {
      if (this[prop] && this[prop].length) {
        return true
      }
      this.$apis.GETREFCDBYREFGRP(data).then((res) => {
        this[prop] = res.content || [];
      });
    },
  },
};
</script>

<style lang="less" scoped>
.upload-print {
  display: flex;
  justify-content: space-between;
  align-items: flex-end;
  .picture {
    flex: 1;
    font-size: 0; // 去除div幽灵字体
  }
}
.ant-btn {
  .icon-class {
    .mg-r(10);
  }
}
.none-label .text-r {
  float: right;
}
.text-left{
  text-align: left;
}
/deep/ .ant-upload {
  width: 100%;
  color: #2b63ff;
  margin: 0;
  border: none;
}
</style>
