<script>
import {mapState} from "vuex"
import AiEartagPicker from "@project/xumu/components/AiEartagPicker.vue";
import AiIdcardRemote from "@project/xumu/components/AiIdcardRemote.vue";

const records = [
  {label: "序号", type: "index"},
  {label: "报案号", prop: "reportNo"},
  {label: "审批状态", prop: "auditStatus", dict: "auditStatus"},
  {label: "审批时间", prop: "auditTime"},
  {label: "审批人", prop: "auditName"},
]
export default {
  name: "loanAdd",
  components: {AiIdcardRemote, AiEartagPicker},
  props: {
    instance: Function,
    permissions: Function,
    dict: Object
  },
  data() {
    return {
      detail: {detailList: []},
      records,
      filterText: "",
      bankList: []
    }
  },
  computed: {
    ...mapState(["user"]),
    userinfo: v => v.user.info || {},
    pageTitle: v => {
      const appName = v.$parent.menuName || v.$parent.$options.label
      return v.isAdd ? `新增${appName}` : v.isAudit ? `${appName}审批` : `${appName}详情`
    },
    isAdd: v => !v.$route.query.id,
    isAudit: v => v.$route.hash == "#audit",
    formImages: v => [
      {label: "身份证(正面)", prop: "frontCard", rules: {required: v.isAdd, message: '请上传 身份证(正面)'}},
      {label: "身份证(反面)", prop: "reverseCard", rules: {required: v.isAdd, message: '请上传 身份证(反面)'}},
      {label: "营业执照", prop: "businessPic", rules: {required: v.isAdd, message: '请上传 营业执照'}},
      {label: "畜禽经营许可证", prop: "breedPic", rules: {required: v.isAdd, message: '请上传 畜禽经营许可证'}},
      {label: "动物防疫条件许可证", prop: "prevention", rules: {required: v.isAdd, message: '请上传 动物防疫条件许可证'}},
    ],
    columns: v => [
      {label: "序号", type: "index"},
      {label: "生物芯片耳标号", prop: "biochipEarNumber"},
      {label: "类别", prop: "category", dict: "category"},
      {label: "品种", prop: "variety", dict: "variety"}
    ].filter(e => !e.hide),
    selectedEartags: v => v.detail.detailList?.length || 0,
    tableData: v => v.detail.detailList?.filter(e => e.biochipEarNumber.indexOf(v.filterText) > -1) || [],
  },
  methods: {
    back(params = {}) {
      this.$router.push(params)
    },
    getDetail() {
      const {id} = this.$route.query
      return id ? this.instance.post("/api/loan/apply/getInfo", null, {params: {id}}).then(res => {
        if (res?.data) {
          const detail = res.data
          detail.detailList = detail.detailList || []
          let {farmPicture: picture} = detail
          picture = JSON.parse(picture || "{}")
          return this.detail = {...detail, ...picture}
        }
      }) : Promise.resolve()
    },
    submit() {
      this.$refs.detail.validate().then(() => {
        const farmPicture = {}
        this.formImages.forEach(e => {
          const {prop} = e
          const val = this.detail[prop]
          if (val) {
            farmPicture[prop] = val
          }
        })
        this.detail.farmPicture = JSON.stringify(farmPicture)
        this.instance.post("/api/loan/apply/addOrEditOffline", {...this.detail}).then(res => {
          if (res?.code == '0') {
            this.$message.success("提交成功!")
            this.back()
          }
        })
      })
    },
    audit() {
      this.$refs.detail.validate().then(() => {
        this.instance.post("/api/loan/apply/audit", {...this.detail}).then(res => {
          if (res?.code == '0') {
            this.$message.success("提交成功!")
            this.back()
          }
        })
      })
    },
    getBanks() {
      this.instance.post("/api/loan/apply/getBank").then(res => {
        if (res?.data) {
          this.bankList = res.data
          this.$set(this.detail, "bankId", res.data?.[0]?.id)
        }
      })
    },
    getProducts(id) {
      const item = this.bankList.find(e => e.id == id)
      return item?.children || []
    },
    getRemoteInfo(userId) {
      userId && this.instance.post("/api/siteUser/querySiteByUserId", null, {
        params: {userId}
      }).then(res => {
        if (res?.data) {
          this.$set(this.detail, "farmId", res.data?.[0]?.id)
        }
      })
    }
  },
  created() {
    this.getDetail().finally(() => this.getBanks())
  }
}
</script>

<template>
  <ai-page :title="pageTitle" class="loanAdd" showBack content-string="blank">
    <el-form size="small" label-width="120px" :model="detail" ref="detail">
      <ai-card title="基础信息">
        <div class="grid">
          <el-form-item label="养殖户" class="row">
            <ai-idcard-remote :instance="instance" @enter="getRemoteInfo"/>
          </el-form-item>
          <el-form-item label="养殖场" prop="farmId" :rules="{required: isAdd,message:'请选择 养殖场'}">
            <ai-select v-if="isAdd" v-model="detail.farmId" :instance="instance" :action="`/api/siteUser/querySiteByUserId?userId=${userinfo.id}`" :prop="{label:'name'}"/>
            <b v-else v-text="detail.farmName"/>
          </el-form-item>
          <el-form-item label="贷款银行" prop="bankId" :rules="{required: isAdd,message:'请选择 贷款银行'}">
            <ai-select v-if="isAdd" v-model="detail.bankId" :select-list="bankList" :prop="{label:'name'}" readonly/>
            <b v-else v-text="detail.bankName"/>
          </el-form-item>
          <el-form-item label="贷款产品" prop="productType" :rules="{required: isAdd,message:'请选择 贷款产品'}">
            <ai-select v-if="isAdd" v-model="detail.productType"
                       :select-list="getProducts(detail.bankId)" :prop="{label:'name',value:'productType'}"/>
            <b v-else v-text="dict.getLabel('loanProduct',detail.productType)"/>
          </el-form-item>
          <el-form-item label="预期贷款额(万)" prop="loanAmount" :rules="{required: isAdd,message:'请输入 预期贷款额'}">
            <ai-input v-model.number="detail.loanAmount" :edit="isAdd"/>
          </el-form-item>
          <el-form-item label="联系人" prop="contacts" :rules="{required: isAdd,message:'请输入 联系人'}">
            <ai-input v-model="detail.contacts" :edit="isAdd"/>
          </el-form-item>
          <el-form-item label="联系电话" prop="phone" :rules="{required: isAdd,message:'请输入 联系电话'}">
            <ai-input v-model="detail.phone" :edit="isAdd"/>
          </el-form-item>
        </div>
      </ai-card>
      <ai-card title="质押标的">
        <template #right>
          <ai-input placeholder="请输入/扫描耳标号" v-model="filterText" class="shrink"/>
          <ai-eartag-picker @select="v=>detail.detailList=v" :instance="instance" v-if="isAdd"
                            :action="`/api/insurance/apply/getEarNumberList?farmId=${detail.farmId}`">
            <el-button type="text">选择</el-button>
          </ai-eartag-picker>
        </template>
        <ai-highlight class="mar-b8 font-14" :content="`拟抵押标的选择 @v 只`" color="red" :value="selectedEartags"/>
        <ai-table :tableData="tableData" :colConfigs="columns" :isShowPagination="!1" hideOptions/>
      </ai-card>
      <ai-card title="证件信息">
        <div v-if="isAdd" class="font-12 color-888">只能上传JPG/PNG文件，且不超过2M</div>
        <div class="grid c-5 el-form--label-top">
          <el-form-item v-for="(img,i) in formImages" :key="i" v-bind="img">
            <ai-uploader :readonly="!isAdd" v-model="detail[img.prop]" :instance="instance" :limit="1" value-is-url/>
          </el-form-item>
        </div>
      </ai-card>
      <ai-card title="银行资料" v-if="isAdd">
        <div class="grid">
          <el-form-item label="贷款合同号" prop="contractNo" :rules="{required:true,message:'请输入贷款合同号'}">
            <ai-input v-model="detail.contractNo"/>
          </el-form-item>
          <el-form-item label="贷款资料" class="sc-2">
            <ai-uploader v-model="detail.picture" value-is-url :instance="instance" :limit="1"/>
          </el-form-item>
          <el-form-item label="说明">
            <ai-input type="textarea" :rows="3" v-model="detail.remarks"/>
          </el-form-item>
        </div>
      </ai-card>
      <ai-card title="审核信息" v-if="!isAdd">
        <div class="grid">
          <template v-if="isAudit">
            <el-form-item label="审批状态" prop="auditStatus" :rules="{required:true,message:'请选择审批状态'}">
              <ai-select v-model="detail.auditStatus" dict="auditStatus"/>
            </el-form-item>
            <el-form-item label="贷款资料" class="sc-3">
              <ai-uploader v-model="detail.picture" value-is-url :instance="instance" :limit="1"/>
            </el-form-item>
            <el-form-item label="贷款合同号" prop="contractNo" :rules="{required:true,message:'请输入 报案号'}">
              <ai-input v-model="detail.contractNo"/>
            </el-form-item>
            <el-form-item label="说明">
              <ai-input type="textarea" :rows="3" v-model="detail.remarks"/>
            </el-form-item>
          </template>
          <template v-else>
            <el-form-item label="审核状态">{{ dict.getLabel('auditStatus', detail.auditStatus) }}</el-form-item>
            <el-form-item label="贷款合同号">{{ detail.contractNo }}</el-form-item>
            <el-form-item label="审核时间">{{ detail.auditTime }}</el-form-item>
            <el-form-item label="贷款资料" class="sc-3">
              <el-image :src="detail.picture" :preview-src-list="[detail.picture]"/>
            </el-form-item>
            <el-form-item label="审核人">{{ detail.auditName }}</el-form-item>
            <el-form-item label="说明">{{ detail.remarks }}</el-form-item>
          </template>
        </div>
      </ai-card>
    </el-form>
    <div slot="footer">
      <el-button v-if="isAdd" type="primary" @click="submit">提交</el-button>
      <el-button v-if="isAudit" type="primary" @click="audit">提交</el-button>
      <el-button @click="back">返回</el-button>
    </div>
  </ai-page>
</template>

<style scoped lang="scss">
.loanAdd {
  :deep(.el-form--label-top) {
    .el-form-item__label {
      width: 100% !important;
    }

    .el-form-item__content {
      margin-left: unset !important;
    }
  }

  .shrink {
    flex-shrink: 0;
  }
}
</style>
