<template>
  <div>
    <el-page-header
      :content="$route.meta.title"
      style="
        padding: 1em;
        font-size: 1em;
        background: #fff;
        margin: 1.67em 0;
        box-shadow: 0 2px 12px 0 rgb(0 0 0 / 10%);
        border-radius: 5px;
      "
      @back="$router.back()"
    >
    </el-page-header>

    <el-row :gutter="24">
      <el-col :span="21" class="print-content">
        <el-card
          id="detail-pictures"
          v-if="
            (detail.id_assets_atlas_files_house_id_relation &&
              detail.id_assets_atlas_files_house_id_relation.length > 0) ||
            (detail.id_assets_atlas_files_land_id_relation &&
              detail.id_assets_atlas_files_land_id_relation.length > 0)
          "
        >
          <div class="el-descriptions__header el-descriptions__title">
            资产图集
          </div>
          <el-carousel trigger="click" height="150px">
            <el-carousel-item
              v-for="item in (detail.id_assets_atlas_files_house_id_relation || detail.id_assets_atlas_files_land_id_relation)"
            >
              <el-image
                style="width: 100%; height: 100%"
                :src="item.url"
                :preview-src-list="picList"
                fit="cover"
              ></el-image>
            </el-carousel-item>
          </el-carousel>
        </el-card>
        <el-card id="detail-info">
          <div class="el-descriptions__header el-descriptions__title">
            基本信息
          </div>
          <el-descriptions
            border
            size="small"
            :column="2"
            :label-style="{ 'font-weight': '600' }"
          >
            <el-descriptions-item
              v-for="item in fields"
              :label="item.name"
              v-if="!['file', 'picture'].find((j) => j === item.field)"
              >{{ contentFormat(item)
              }}{{ units.get(item.field) }}</el-descriptions-item
            >
            <el-descriptions-item :label="'关联'+(detail.hasOwnProperty('id_houses_land_id_relation') ? '房产' : '土地')">
              <div style="display: flex;align-items: center;">
                <span>{{ detail.hasOwnProperty('id_houses_land_id_relation') ? (detail.id_houses_land_id_relation ? detail.id_houses_land_id_relation.name : '') : (detail.land_id_lands_id_relation ? detail.land_id_lands_id_relation.name : '')  }}</span>
                <el-link style="margin-left: 10px;white-space: nowrap;" @click="$router.push(detail.hasOwnProperty('id_houses_land_id_relation') ? (detail.id_houses_land_id_relation ? ('/houseDetail/'+detail.id_houses_land_id_relation.id) : '') : (detail.land_id_lands_id_relation ? ('/landDetail/'+detail.land_id_lands_id_relation.id) : ''))">查看</el-link>
              </div>
            </el-descriptions-item>
          </el-descriptions>
        </el-card>

        <el-card id="detail-documents">
          <div class="el-descriptions__header el-descriptions__title">
            资产证件图片
          </div>
          <template>
            <template
              v-if="
                (detail.id_asset_picture_files_land_id_relation &&
                detail.id_asset_picture_files_land_id_relation.length > 0) ||
                (detail.id_asset_picture_files_house_id_relation &&
                detail.id_asset_picture_files_house_id_relation.length > 0)
              "
            >
              <div
                v-for="item in /\/land/g.test($route.path) ? detail.id_asset_picture_files_land_id_relation : detail.id_asset_picture_files_house_id_relation"
              >
                <el-image
                  style="width: 100%; height: 100%"
                  :src="item.url"
                  :preview-src-list="
                    (/\/land/g.test($route.path) ? detail.id_asset_picture_files_land_id_relation : detail.id_asset_picture_files_house_id_relation).map(
                      (i) => i.url
                    )
                  "
                  fit="contain"
                ></el-image>
              </div>
            </template>
            <template v-else>
              <el-empty description="无"></el-empty>
            </template>
          </template>
        </el-card>
        <el-card id="detail-histories">
          <div class="el-descriptions__header el-descriptions__title">
            历史沿革
          </div>
          <template>
            <template v-if="histories && histories.length > 0">
              <Timeline>
                <TimelineItem v-for="(item, index) in histories" :key="item.id">
                  <el-descriptions :column="1" size="mini" border :title="$moment(item.fashengshijian).format('YYYY-MM-DD HH:mm')" :label-style="{ 'width': '86px' }">
                    <el-descriptions-item>
                      <template slot="label">
                        <i class="el-icon-coordinate"></i>
                        面积调整
                      </template>
                      {{ item.mianjitiaozheng }}
                    </el-descriptions-item>
                    <el-descriptions-item>
                      <template slot="label">
                        <i class="el-icon-office-building"></i>
                        资产来源
                      </template>
                      {{ item.zichanlaiyuan }}
                    </el-descriptions-item>
                    <el-descriptions-item>
                      <template slot="label">
                        <i class="el-icon-chat-line-square"></i>
                        其他说明
                      </template>
                      {{ item.qitashuoming }}
                    </el-descriptions-item>
                    <el-descriptions-item>
                      <template slot="label">
                        <i class="el-icon-picture-outline"></i>
                        相关图片
                      </template>
                      <div style="display: flex;flex-wrap: wrap;padding-top: 10px;">
                        <div style="display: flex;flex-direction: column; align-items: center;margin-right: 16px;" v-for="(img,index) in item.id_his_tupian_files_asset_history_id_relation" :key="img.id">
                          <el-image
                            style="height: 160px"
                            :src="img.url"
                            fit="contain"
                          ></el-image>
                          <div style="color: #3477c6;padding: 10px 0;">{{ ++index }}. <span style="font-weight: 600;">{{ img.original_name }}</span></div>
                        </div>
                      </div>
                    </el-descriptions-item>
                  </el-descriptions>

                </TimelineItem>
              </Timeline>
            </template>
            <template v-else>
              <el-empty description="无"></el-empty>
            </template>
          </template>
        </el-card>
        <el-card id="detail-assetsMap">
          <div class="el-descriptions__header el-descriptions__title">
            资产地图
          </div>

          <div
            class="map"
            id="detail-map"
            style="width: 100%; height: 300px"
          ></div>
        </el-card>
        <el-card id="detail-safe">
          <div class="el-descriptions__header el-descriptions__title">
            安全检查
          </div>
        </el-card>

        <el-card id="detail-contract">
          <div class="el-descriptions__header el-descriptions__title">
            租赁合同
          </div>

          <xy-table :is-page="false" :height="300" :list="/\/land/g.test(this.$route.path) ? detail.id_leases_land_id_relation : detail.id_leases_house_id_relation" :table-item="leaseTable" style="margin-top: 20px" size="mini" stripe ref="table1" :auths="[]" ></xy-table>
        </el-card>

        <el-card id="detail-repair">
          <div class="el-descriptions__header el-descriptions__title">
            维修保养
          </div>
        </el-card>

        <el-card id="detail-files">
          <div class="el-descriptions__header el-descriptions__title">
            资产相关附件
          </div>
          <template>
            <template
              v-if="
                (detail.id_asset_file_files_land_id_relation &&
                detail.id_asset_file_files_land_id_relation.length > 0) ||
                 (detail.id_asset_file_files_house_id_relation &&
                detail.id_asset_file_files_house_id_relation.length > 0)
              "
            >
              <div
                v-for="item in /\/land/g.test($route.path) ? detail.id_asset_file_files_land_id_relation : detail.id_asset_file_files_house_id_relation"
                style="display: flex; justify-content: space-between;margin-bottom: 4px;"
              >
                <a :download="item.url">{{ item.original_name }}</a>
                <div>
                  <el-button
                    type="primary"
                    icon="el-icon-download"
                    circle
                    size="mini"
                    @click="down(item)"
                  ></el-button>
                  <el-button
                    type="primary"
                    icon="el-icon-search"
                    circle
                    size="mini"
                    @click="open(item.url)"
                  ></el-button>
                </div>
              </div>
            </template>
            <template v-else>
              <el-empty description="无"></el-empty>
            </template>
          </template>
        </el-card>
      </el-col>
      <el-col :span="3">
        <Anchor show-ink :offset-top="64">
          <AnchorLink href="#detail-pictures" title="资产图集"  v-if="
            (detail.id_assets_atlas_files_house_id_relation &&
              detail.id_assets_atlas_files_house_id_relation.length > 0) ||
            (detail.id_assets_atlas_files_land_id_relation &&
              detail.id_assets_atlas_files_land_id_relation.length > 0)
          " />
          <AnchorLink href="#detail-info" title="基本信息" />
          <AnchorLink href="#detail-documents" title="证件图片" />
          <AnchorLink href="#detail-histories" title="历史沿革" />
          <AnchorLink href="#detail-assetsMap" title="资产地图" />
          <AnchorLink href="#detail-safe" title="安全检查"></AnchorLink>
          <AnchorLink href="#detail-contract" title="租赁合同"></AnchorLink>
          <AnchorLink href="#detail-repair" title="维修保养"></AnchorLink>
          <AnchorLink href="#detail-files" title="相关附件" />
        </Anchor>
      </el-col>
    </el-row>

    <Modal
      :width="76"
      transfer
      :z-index="6000"
      v-model="showModal"
      :footer-hide="true"
      title="预览"
    >
      <template>
        <iframe
          style="width: 100%; height: 57vh"
          :src="codeUri"
          border="0"
        ></iframe>
      </template>
    </Modal>

    <div style="position:fixed;right: 40px;bottom: 80px;background: #fff;border-radius: 100%;width: 40px;height: 40px;display: flex;align-items: center;justify-content: center;font-size: 20px;cursor: pointer;" @click="print">
      <Icon type="md-print" />
    </div>
  </div>
</template>

<script>
import html2canvas from "html2canvas";

import { show, index } from "@/api/system/baseForm";
import { show as formShow } from "@/api/system/customForm";
import { getparameter } from "@/api/system/dictionary";
import { listdept } from "@/api/system/department";
import { download } from "@/utils/downloadRequest";
export default {
  name: "detail",
  data() {
    return {
      showModal: false,
      codeUri: "",
      center: [120.283692, 31.614211],
      marker: {},

      detail: {},
      fields: [],
      relation: [],
      customForm: {
        customFormId: "",
        tableName: "",
      },

      histories: [],
      units: new Map([
        ["dengjimianji", "m²"],
        ["shijimianji", "m²"],
        ["dikuaizongjia", "元"],
        ["dikuaimianji", "m²"],
        ["muqianjunjia", "元"],
      ]),

      leaseTable: [
        {
          fixed: 'left',
          type: 'index',
          width: 46,
        },
        {
          label: '地块名称',
          prop: 'dikuaimingcheng',
          width: 180,
          fixed: 'left',
          align: 'left'
        },
        {
          label: '出租房',
          prop: 'chuzufang',
          width: 150
        },
        {
          label: '承租方',
          prop: 'chengzufang',
          width: 150
        },
        {
          label: '租赁期限',
          width: 190,
          customFn:row => {
            return (
              <div>
                <span>{ this.$moment(new Date(row.zulinkaishiqixian)).format('YYYY.MM.DD') }</span>
                <span> - </span>
                <span>{ this.$moment(new Date(row.zulinjieshuqixian)).format('YYYY.MM.DD') }</span>
              </div>
            )
          }
        },
        {
          label: '应收租金',
          prop: 'yingshouzujin',
          align: 'right',
          width: 120
        },
        {
          label: '实收租金',
          prop: 'shishouzujin',
          align: 'right',
          width: 120
        },
        {
          label: '保证金',
          prop: 'baozhengjin',
          width: 120,
          customFn:row => {
            return (
              <div style={{'text-align': row.baozhengjin === '无' ? 'center' : 'right' }}>{ row.baozhengjin }</div>
            )
          }
        },
        {
          label: '未到位原因',
          prop: 'weidaoweiyuanyin',
          minWidth: 140
        }
      ]
    };
  },
  methods: {
    open(url) {
      this.codeUri = `${process.env.VUE_APP_PREVIEW}?url=${encodeURIComponent(
        new Buffer(url).toString("base64")
      )}`;

      this.showModal = true;
    },

    down(e) {
      download(e.url, "get", {}, e.original_name);
    },

    init() {
      this.map = new AMap.Map("detail-map", {
        center: this.center,
        mapStyle: "amap://styles/bfb1bb3feb0db7082367abca96b8d214", // 设置地图的显示样式
        zoom: 60,
      });

      this.map.remove(this.marker);
      if (this.detail.zichanweizhi) {
        let lat, lng;
        [lng, lat] = this.detail.zichanweizhi.split(",");
        let marker = new AMap.Marker({
          icon: "//a.amap.com/jsapi_demos/static/demo-center/icons/poi-marker-default.png",
          position: [Number(lng), Number(lat)],
          offset: new AMap.Pixel(-13, -30),
        });
        let markerContent = document.createElement("div");
        markerContent.setAttribute("class", "map-marker");
        let markerImg = document.createElement("img");
        markerImg.src =
          "//a.amap.com/jsapi_demos/static/demo-center/icons/poi-marker-default.png";
        let markerSpan = document.createElement("span");
        markerSpan.setAttribute("class", "map-marker__text");
        markerSpan.innerText = this.detail.name;
        markerContent.appendChild(markerImg);
        markerContent.appendChild(markerSpan);
        marker.setContent(markerContent);

        this.marker = marker;
        this.map.add(this.marker);
        this.map.setFitView(this.marker);
      }
    },

    async getFields() {
      if (this.$route.meta.params?.custom_form) {
        let decode = decodeURIComponent(this.$route.meta.params?.custom_form);
        try {
          let custom_form = JSON.parse(decode);
          this.customForm.customFormId = custom_form.custom_form_id;
          this.customForm.tableName = custom_form.table_name;
        } catch (err) {
          console.warn(err);
        }
      }

      const res = await formShow({ id: this.customForm.customFormId }, false);
      this.fields = res.fields.filter(i => i.list_show).sort((a, b) => a.sort - b.sort);
      this.relation = res.relation;

      //字段处理
      //初始表白名单
      let baseTable = new Map([
        [
          "departments",
          async () => {
            const res = await listdept();
            return res;
          },
        ],
        ["admins", []],
      ]);
      let { fields, relation } = this;
      if (
        !fields ||
        !relation ||
        !fields instanceof Array ||
        !relation instanceof Array
      ) {
        throw new Error("fields或relation格式错误");
      }
      fields
        .forEach((i) => {
          i._relations = relation.find(
            (j) => j.link_table_name.split("_")[1] === i.field
          );
          if (i.select_item && typeof i.select_item === "object") {
            let keys = Object.keys(i.select_item);
            i._params = keys.map((key) => {
              return {
                key,
                value: /^\d*$/.test(i.select_item[key])
                  ? Number(i.select_item[key])
                  : i.select_item[key],
              };
            });
          }
          if (i.edit_input === "file" || i.edit_input === "files") {
            return;
          }
          if (i._relations) {
            if (baseTable.get(i._relations.link_table_name)) {
              baseTable
                .get(i._relations.link_table_name)()
                .then((res) => {
                  i._params = res.data;
                });
            } else {
              i._params = i._relations.parameter_id
                ? getparameter({ id: i._relations.parameter_id }, false).then(
                    (res) => {
                      i._params = res.detail;
                    }
                  )
                : this.index({
                    table_name: i._relations.link_table_name,
                    page: 1,
                    page_size: 9999,
                  }).then((res) => {
                    i._params = res.data;
                  });
            }
          }
        });

      const detail = await show({
        id: this.$route.params.id,
        table_name: this.customForm.tableName,
      });
      this.detail = detail;
      this.init();
    },


    async getHistories () {
      const res = await index({
        table_name: 'his_evolutions',
        page: 1,
        page_size: 999,
        sort_name: "fashengshijian",
        filter:[
          {
            key: /\/land/g.test(this.$route.path) ? 'land_id' : 'house_id',
            op: 'eq',
            value: this.$route.params.id
          }
        ]
      })
      this.histories = res.data;
    },

    print () {
      const iframeEL=document.querySelector('.print-iframe');
      if(iframeEL){
        iframeEL.remove();
      }
      const dom = document.querySelector('.print-content')
      html2canvas(dom,{
        useCORS: true,
        ignoreElements:ele => {
          const ignoreIds = ['detail-pictures']
          if (ignoreIds.indexOf(ele.id) !== -1) {
            return true
          }
        }
      }).then(canvas => {
        const img = new Image();
        img.src = canvas.toDataURL('image/png');
        img.style.width='100%'
        // 在 iframe 文档中添加图片元素
        const iframe = document.createElement('iframe');
        iframe.style.width='100%'
        iframe.classList.add('print-iframe')
        document.body.appendChild(iframe)
        const doc = iframe.contentWindow.document
        doc.body.appendChild(img);
        //避免图片没有加载完成就打印
        setTimeout(()=>{
          iframe.contentWindow.print();
        },100)
      })
    }
  },

  computed: {
    picList() {
      if (/\/house/g.test(this.$route.path)) {
        return (
          this.detail?.id_assets_atlas_files_house_id_relation?.map(
            (i) => i.url
          ) || []
        );
      }
      if (/\/land/g.test(this.$route.path)) {
        return (
          this.detail?.id_assets_atlas_files_land_id_relation?.map(
            (i) => i.url
          ) || []
        );
      }
    },
    contentFormat() {
      return function (i) {
        let { field, _relations } = i;
        if (field === 'bufuqingkuang') {
          if ((this.detail.tudiquanshuren !== this.detail.quanliren) ||
            (this.detail.dengjimianji !== this.detail.shijimianji)) {
            let text = ""
            text += this.detail.tudiquanshuren !== this.detail.quanliren
              ? " 权利人名称不符 "
              : ""
            text += this.detail.dengjimianji !== this.detail.shijimianji
              ? " 登记面积不符 "
              : ""
            return text;
          }
          return "无"
        }
        if (_relations && _relations.link_table_name) {
          if (
            _relations.link_relation === "hasOne" ||
            _relations.link_relation === "newHasOne"
          ) {
            return (
              this.detail[_relations.link_with_name]?.name ||
              this.detail[_relations.link_with_name]?.no ||
              this.detail[_relations.link_with_name]?.value
            );
          }
          if (
            _relations.link_relation === "hasMany" ||
            _relations.link_relation === "newHasMany"
          ) {
            return this.detail[_relations.link_with_name]
              ?.map((o) => o?.original_name || o?.name || o?.no || o?.value)
              ?.toString();
          }

          return;
        }
        if (i._params && i._params.length > 0) {
          return i._params.find((j) => j.value == this.detail[i.field])?.key;
        }

        return this.detail[i.field];
      };
    },
  },
  created() {
    this.getFields().then(res => {
      this.getHistories()
    })
  },
};
</script>

<style scoped lang="scss">
.el-card__body > .el-descriptions__title,.el-card__body > ::v-deep .el-descriptions__title {

  position: relative;
  padding-left: 14px;

  &::before {
    content: '';
    width: 4px;
    background: linear-gradient(to bottom,rgb(57, 129, 199), rgba(118, 148, 183, 0.7));

    position: absolute;
    left: 0;
    top: 2px;
    bottom: 2px;
  }
}
::v-deep .el-card {
  margin-bottom: 20px;
}
::v-deep .el-empty__image {
  width: 120px;
}

a {
  color: red;
  text-decoration: none;
  transition: all 0.2s;
}

a:hover {
  color: red;
  text-decoration: underline;
}

::v-deep .ivu-anchor-link-title:hover {
  transition: all 0.2s;
  color: $primaryColor !important;
}

.el-image + .el-image {
  margin-left: 6px;
}
</style>
<style lang="scss">
.map-marker {
  display: flex;
  flex-direction: column;
  align-items: center;

  &__text {
    background: #fff;
    zoom: 0.9;
    padding: 2px 6px;
    border-radius: 4px;
    white-space: nowrap;
    filter: drop-shadow(2px 2px 5px #00000055);
  }
}
</style>
