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

const columns = [
  { label: "序号", type: "index" },
  { label: "生物芯片耳标号", prop: "biochipEarNumber" },
  { label: "类别", prop: "category", dict: "category" },
  { label: "品种", prop: "variety", dict: "variety" },
]
export default {
  name: "iaAdd",
  components: { AiIdcardRemote, AiEartagPicker, AiAudit },
  props: {
    instance: Function,
    permissions: Function,
    dict: Object
  },
  data() {
    return {
      detail: { detailList: [] },
      columns,
      companyList: []
    }
  },
  computed: {
    ...mapState(["user"]),
    userinfo: v => v.user.info || {},
    pageTitle: v => {
      const appName = v.$parent.menuName || v.$parent.$options.label
      return v.$route.query.id ? v.isEdit ? `编辑${appName}` : `${appName}详情` : `新增${appName}`
    },
    isAdd: v => !v.$route.query.id,
    isEdit: v => v.$route.query.edit == 1,
    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: '请上传 动物防疫条件许可证' } },
    ]
  },
  methods: {
    back(params = {}) {
      this.$router.push(params)
    },
    getDetail() {
      const { id } = this.$route.query
      return id ? this.instance.post("/api/insurance/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()
    },
    getCompanies() {
      this.instance.post("/api/insurance/apply/getCompany").then(res => {
        if (res?.data) {
          this.companyList = res.data
          this.$set(this.detail, "companyId", res.data?.[0]?.id)
        }
      })
    },
    getProducts(id) {
      const item = this.companyList.find(e => e.id == id)
      return item?.children || []
    },
    submit() {
      this.$refs.detail.validate().then(() => {
        const earNumberList = this.detail.detailList.map(e => e.biochipEarNumber)
        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/insurance/apply/addOrEditOffline", { ...this.detail, earNumberList }).then(res => {
          if (res?.code == 0) {
            this.$message.success("提交成功!")
            this.back()
          }
        })
      })
    },
    handleAudit() {
      this.$refs.detail.validate().then(() => {
        this.instance.post("/api/insurance/apply/audit", this.detail).then(res => {
          if (res?.code == 0) {
            this.$message.success("提交成功!")
            this.back()
          }
        })
      })
    },
    getRemoteInfo(userId) {
      userId && this.instance.post("/api/siteUser/querySiteByUserId", null, {
        params: { userId }
      }).then(res => {
        if (res?.data?.[0]) {
          const { id } = res.data[0]
          this.$set(this.detail, "farmId", id)
          this.$set(this.detail, "targetUser", userId)
        }
      })
    }
  },
  created() {
    this.getDetail().finally(() => this.getCompanies())
  }
}
</script>

<template>
  <ai-page :title="pageTitle" class="iaAdd" 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 || isEdit, message: '请选择 养殖场' }">
            <ai-select v-if="isAdd || isEdit" v-model="detail.farmId" :instance="instance"
              :action="`/api/siteUser/querySiteByUserId?userId=${detail.targetUser}`" :prop="{ label: 'name' }" />
            <b v-else v-text="detail.farmName" />
          </el-form-item>
          <el-form-item label="承保公司" prop="companyId" :rules="{ required: isAdd || isEdit, message: '请选择 承保公司' }">
            <ai-select v-if="isAdd || isEdit" v-model="detail.companyId" :select-list="companyList"
              :prop="{ label: 'name' }" disabled />
            <b v-else v-text="detail.companyName" />
          </el-form-item>
          <el-form-item label="保险产品" prop="productType" :rules="{ required: isAdd || isEdit, message: '请选择 保险产品' }">
            <ai-select v-if="isAdd || isEdit" v-model="detail.productType" :select-list="getProducts(detail.companyId)"
              :prop="{ label: 'name', value: 'productType' }"
              @select="v => $set(detail, 'insureType', v.children[0].insureType)" />
            <b v-else v-text="dict.getLabel('productType', detail.productType)" />
          </el-form-item>
          <el-form-item label="投保类型">
            <ai-input :value="dict.getLabel('insureType', detail.insureType)" placeholder="根据保险产品自动带出"
              :edit="isAdd || isEdit" readonly />
          </el-form-item>
          <el-form-item label="联系人">
            <ai-input v-model="detail.contacts" :edit="isAdd || isEdit" />
          </el-form-item>
          <el-form-item label="联系电话">
            <ai-input v-model="detail.phone" :edit="isAdd || isEdit" />
          </el-form-item>
        </div>
      </ai-card>
      <ai-card title="投保对象">
        <template #right v-if="isAdd">
          <ai-eartag-picker @select="v => detail.detailList = v" :instance="instance"
            :action="`/api/insurance/apply/getEarNumberList?farmId=${detail.farmId}`">
            <el-button type="text">选择</el-button>
          </ai-eartag-picker>
        </template>
        <ai-table :tableData="detail.detailList" :colConfigs="columns" :isShowPagination="!1" hideOptions />
      </ai-card>
      <ai-card title="证件信息">
        <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 v-if="isAdd || isEdit" v-model="detail[img.prop]" :instance="instance" :limit="1"
              value-is-url />
            <el-image :src="detail[img.prop]" :preview-src-list="[detail[img.prop]]" v-else />
          </el-form-item>
        </div>
      </ai-card>
      <ai-card title="审核信息" v-if="!(isAdd || isAudit)">
        <el-form-item label="审核状态">{{ dict.getLabel('auditStatus', detail.auditStatus) }}</el-form-item>
        <el-form-item label="保单资料" class="sc-4">
          <el-image :src="detail.picture" :preview-src-list="[detail.picture]" />
        </el-form-item>
        <el-form-item label="审核时间">{{ detail.auditTime }}</el-form-item>
        <el-form-item label="审核人">{{ detail.auditName }}</el-form-item>
        <el-form-item label="保单订单号">{{ detail.orderNo }}</el-form-item>
        <el-form-item label="说明">{{ detail.remarks }}</el-form-item>
      </ai-card>
      <ai-card title="保险资料" v-if="isAudit">
        <div class="grid">
          <el-form-item label="审批" prop="auditStatus"
            :rules="[{ required: true, type: 'enum', enum: [2, 3], message: '请选择是否同意' },]">
            <ai-audit @change="v => $set(detail, 'auditStatus', v)" />
          </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="orderNo" :rules="{ required: true, message: '请输入 保单订单号' }"
            v-if="detail.auditStatus == 2">
            <ai-input v-model="detail.orderNo" />
          </el-form-item>

          <el-form-item label="说明">
            <ai-input type="textarea" :rows="3" v-model="detail.remarks" />
          </el-form-item>
        </div>
      </ai-card>
    </el-form>
    <div slot="footer">
      <template v-if="isAdd || isEdit">
        <el-button type="primary" @click="submit">提交</el-button>
      </template>
      <el-button v-if="isAudit" type="primary" @click="handleAudit">提交</el-button>
      <el-button @click="back">返回</el-button>
    </div>
  </ai-page>
</template>

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

    .el-form-item__content {
      margin-left: unset !important;
    }
  }
}
</style>
