<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-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-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-col>
        <a-col :xl="4" :lg="6" :sm="12">
          <a-form-model-item label="保险公司" prop="payorCode">
            <a-select v-model="form.payorCode" placeholder="请选择保险公司" show-search allow-clear @filterOption="filterCode" @change="payorChange">
              <a-select-option v-for="item in companyCode" :key="item.payorCode" :value="item.payorCode">
                {{ 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="corpCode">
            <a-select v-model="form.corpCode" placeholder="请选择客户公司名称" show-search allow-clear @filterOption="filterCode" @change="corpChange" @search="corpSearch">
              <a-select-option v-for="item in comCorpCode" :key="item.corpCode" :value="item.corpCode">
                {{ 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="policyNo">
            <a-input allow-clear v-model="form.policyNo" placeholder="请输入保单卡号"></a-input>
          </a-form-model-item>
        </a-col>
        <a-col :xl="4" :lg="6" :sm="12">
          <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-col>
        <a-col :xl="4" :lg="6" :sm="12">
          <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-col>
        <a-col :xl="4" :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="planCode">
            <a-select v-model="form.planCode" placeholder="请选择保险计划" show-search allow-clear @filterOption="filterCode" @search="codeSearch">
              <a-select-option v-for="item in comPlanCode" :key="item.planCode" :vlaue="item.planCode">
                {{ 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-col :xl="4" :lg="6" :sm="12">
          <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="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-row>
      <a-row>
        <a-col :xl="9" :sm="12">
          <a-form-model-item label="保卡复印件" prop="medCardCopeFiles">
            <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">
          <a-form-model-item label="身份证复印件" prop="idCardCopeFiles">
            <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>
              <a-button type="primary" class="mar-left10" ghost>打印</a-button>
            </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 type="primary" class="mar-left10 text-r" @click="handlerReset">
              <Icon name="ssireset" :size="14" />重置
            </a-button>
            <a-button class="mar-left10 text-r" type="primary" @click="handlerSave">
              <Icon name="ssidownload" :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: {
        payorCode: undefined,
        corpCode: undefined,
        planCode: undefined,
        waitingPeriod: "N",
        isUndertakeAnamnesis: "N",
        medCardCopeFiles: [],
        idCardCopeFiles: [], // 身份证复印件
      },
      medCardCopeFiles: [],
      idCardCopeFiles: [], // 身份证复印件
      previewImage: "",
      companyCode: [],
      corpCode: [],
      comCorpCode: [],
      planCode: [],
      comPlanCode: [],
      formRules: {},
    };
  },
  mounted() {
    if (this.$route.query && this.$route.query.id) {
      this.getCustomerDetail(this.$route.query);
    }
    this._getPayorCode();
  },
  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: "customerInfo",
              query: { id, 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.corpCode = 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 } = params;
      const data = {
        id: id && id * 1,
        patientPolicyId: patientPolicyId * 1,
      };
      this.$apis.GETCUSTOMERDETAIL(data).then((res) => {
        if (res.returnCode === "0000") {
          this.form = res.content || {};
          this._getCorporateCode(this.form.payorCode);
          this._getPlanCode(this.form.corpCode);
          const medCardCopeFiles = this.form.medCardCopeFiles || [];
          const idCardCopeFiles = this.form.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,
            })
          })
        }
        // 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) {
      this.form.planCode = undefined;
      if (!val) {
        return false;
      }
      // this.form.corpCode = 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[i].splice(i, 1);
          this.form.medCardCopeFiles[i].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[i].splice(i, 1);
          this.form.idCardCopeFiles[i].splice(i, 1);
          return true;
        }
      }
    },
    handlePreview(file) {
      this.previewImage = file.url;
      this.previewVisible = true;
    },
    handleClose() {
      this.previewVisible = false;
    },
    // 选择框筛选
    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: "",
          payorCode: val,
        }).then((res) => {
          this.corpCode = res.content || [];
          this.comCorpCode = res.content || [];
        });
    },
    _getPlanCode(val) {
      this.$apis.GETPLANCODEBYCORP({
          longName: "",
          corpCdoe: val,
        }).then((res) => {
          this.planCode = res.content || [];
          this.comPlanCode = 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-align: right;
}
/deep/ .ant-upload {
  width: 100%;
  color: #2b63ff;
  margin: 0;
  border: none;
}
</style>
