<template>
  <div style="padding: 0 20px;">
    <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="20">
      <el-col :span="24">
        <el-card>
          <div class="el-descriptions__header el-descriptions__title">
            基本信息
          </div>
          <el-descriptions
            border
            :column="2"
            :label-style="{ 'font-weight': '600' }"
          >
            <el-descriptions-item
              v-for="item in showFields"
              :label="item.name"
              v-if="!['file', 'picture'].find((j) => j === item.field)"
            >
              <template v-if="item.edit_input === 'richtext'">
                <div v-html="detail[item.field]"></div>
              </template>
              <template v-else-if="item.edit_input === 'file'">
                <div>img</div>
              </template>
              <template v-else-if="item.edit_input === 'files'">
                <div
                  v-for="(item, index) in detail[`${item.field}_upload_details`]"
                  style="display: flex; justify-content: space-between;margin-bottom: 4px;"
                >
                  <a :download="item.url">{{++index}}.{{ 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-view"
                      circle
                      size="mini"
                      @click="open(item.url)"
                    ></el-button>
                  </div>
                </div>
              </template>
              <template v-else>
                {{ contentFormat(item) }}
              </template>
            </el-descriptions-item
            >
          </el-descriptions>
        </el-card>

        <el-card>
          <div class="el-descriptions__header el-descriptions__title">
            标的物
          </div>
          <xy-table size="mini" :height="300" :is-page="false" :list="detail.lets_to_assets || []" :table-item="assetTable"></xy-table>
        </el-card>
      </el-col>
    </el-row>

    <el-backtop></el-backtop>

    <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>
</template>

<script>
import { show, index } from "@/api/system/baseForm";
import { show as formShow, index as customFormIndex } 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: "",

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

      allTables: [],
      linkTableList: [],
      assetTable: [
        {
          "prop": "name",
          "label": "资产名称",
          "width": 0,
          "fixed": "left",
          "align": "left",
          customFn: row => {
            return (<span>{ row.land_id ? row.lands.name : row.house.name }</span>)
          }
        },
        {
          prop: "type",
          label: "分类",
          "fixed": "left",
          customFn: row => (
            <span>{ row.land_id ? '房产' : '土地' }</span>
          )
        },
        {
          "prop": "zuoluo",
          "label": "坐落",
          "width": 0,
          "align": "left",
          customFn: row => {
            return (<span>{ row.land_id ? row.lands.zuoluo : row.house.zuoluo }</span>)
          }
        },
        {
          "prop": "shijimianji",
          "label": "实际面积（m²）",
          "width": 0,
          "align": "center",
          customFn: row => {
            return (<span>{ row.land_id ? row.lands.shijimianji : row.house.shijimianji }</span>)
          }
        },
        {
          "prop": "chuzumianji",
          "label": "出租面积（m²）",
          "width": 160,
        },
      ]
    };
  },
  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);
    },

    formatColumn (info) {
      let table = [];
      //字段处理
      //初始表白名单
      let baseTable = new Map([
        ['departments', async () => {
          const res = await listdept()
          return res
        }],
        ['admins',[]]
      ])
      let { fields, relation } = info;
      let fieldRes = fields.sort((a,b) => a.sort - b.sort)
      if (
        !fields ||
        !relation ||
        !fields instanceof Array ||
        !relation instanceof Array
      ) {
        throw new Error("fields或relation格式错误");
      }
      fieldRes?.forEach((i, index) => {
        i._relations = relation.find((j) => j.custom_form_field === 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: 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)
          } 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;
              });
          }
        }
      });
      fields
        ?.filter((i) => i.list_show)
        .forEach((i) => {
          if (i._relations) return
          let linkOb = {};

          if (i.edit_input === "richtext") {
            linkOb.customFn = (row) => {
              return (
                <div
                  style={{ "max-height": "55px","overflow": "scroll" }}
                  domPropsInnerHTML={row[i.field]}
                ></div>
              );
            };
          }
          if (
            i.select_item &&
            typeof i.select_item === "object" &&
            !(i.select_item instanceof Array)
          ) {
            let keys = Object.keys(i.select_item);
            linkOb.customFn = (row) => {
              let paramMap = new Map();
              keys.forEach((key) => {
                paramMap.set(i.select_item[key], key);
              });

              return <span>{paramMap.get(row[i.field]?.toString())}</span>;
            };
          }
          if (i._relations) {
            let { link_relation, foreign_key, link_with_name } = i._relations;
            if (link_relation === "newHasOne" || link_relation === "hasOne") {
              linkOb.customFn = (row) => {
                if (i.edit_input === "file") {
                  return (
                    <a
                      download={row[link_with_name]?.original_name}
                      href={row[link_with_name]?.url}
                    >
                      {row[link_with_name]?.original_name}
                    </a>
                  );
                } else {
                  return (
                    <span>
                      {row[link_with_name]?.name ||
                        row[link_with_name]?.no ||
                        row[link_with_name]?.value}
                    </span>
                  );
                }
              };
            }

            if (link_relation === "hasMany" || link_relation === "newHasMany") {
              linkOb.customFn = (row) => {
                if (i.edit_input === "files") {
                  return (
                    <div style="display: flex;flex-direction: column;">
                      {row[link_with_name]?.map((o) => (
                        <a>
                          { o?.original_name || o?.name }
                        </a>
                      ))}
                    </div>
                  )
                } else {
                  return (
                    <div>
                      {row[link_with_name]?.map((o) => (
                        <p>
                          {o?.name ||
                            o?.no ||
                            o?.value ||
                            o?.biaoti ||
                            o?.mingcheng}
                        </p>
                      ))}
                    </div>
                  );
                }
              };
            }
          }
          table.push(
            Object.assign(
              {
                prop: i.field,
                label: i.name,
                width: i.width,
                fixed: i.is_fixed,
              },
              linkOb
            )
          );
        });
      table.unshift({
        type: "index",
        width: 60,
        label: "序号",
      });

      return table;
    },

    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.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
        .sort((a, b) => a.sort - b.sort)
        .forEach((i) => {
          i._relations = relation.find(
            (j) => j.custom_form_field === 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;
    },

  },

  computed: {
    showFields () {
      return this.fields.filter(field => (!field._relations || field._relations.link_relation === 'hasOne' || field._relations.link_relation === 'newHasOne'))
    },
    contentFormat() {
      return function (i) {
        let { _relations } = i;
        if (_relations && _relations.link_table_name) {
          if (
            _relations.link_relation === "hasOne" ||
            _relations.link_relation === "newHasOne"
          ) {
            return (
              this.detail[_relations.link_with_name]?.original_name ||
              this.detail[_relations.link_with_name]?.name ||
              this.detail[_relations.link_with_name]?.no ||
              this.detail[_relations.link_with_name]?.value ||
              this.detail[_relations.link_with_name]?.mingcheng
            );
          }

          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(_ => {
    })
  },
};
</script>

<style scoped lang="scss">
::v-deep .el-card {
  margin-bottom: 20px;
}
::v-deep .el-empty__image {
  width: 120px;
}

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

a:hover {
  color: $primaryColor;
  text-decoration: underline;
}

.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;
  }
}
</style>
