<script>
import { save, show, index, destroy } from "@/api/system/baseForm";
import { CreateDialog } from "@/utils/createDialog"
import { deepCopy } from "@/utils";
import { resolveFormInfo } from '@/utils/createTable'
export default {
  props: {
    tableName: String,
  },
  render(h) {
    const _this = this;
    let dialog = new CreateDialog(this,[
      {
        sort: 0,
        key: "land_list",
        label: "土地选择",
        render: h('div',[
          h('Button', {
            props: {
              type: "primary"
            },
            on: {
              ["click"]() {
                _this.landDialog = true;
              }
            },
          },"选择土地"),
          h('div', _this.selectedLands?.map(item => h('Tag',{ props: { color: "primary" } }, item.name)))
        ])
      },
      {
        sort: 1,
        key: "house_list",
        label: "房产选择",
        render: h('div',[
          h('Button', {
            props: {
              type: "primary"
            },
            on: {
              ["click"]() {
                _this.houseDialog = true;
              }
            },
          },"选择房产"),
          h('div', _this.selectedHouses?.map(item => h('Tag',{ props: { color: "primary" } }, item.name)))
        ])
      }
    ],{
      width: "1000px"
    })

    return (
      <div>
        {
          dialog.render()
        }

        <el-drawer title="土地列表"
                   visible={this.landDialog}
                   size="64%"
                   on={{
                     ['update:visible']: (val) => this.landDialog = val,
                   }}>
          <div style="padding: 0 10px;">
            <xy-table
              ref="landLinkTable"
              table-item={
                [
                  {
                    type: "selection",
                    width: 56,
                    align: "center",
                    reserveSelection: true,
                    fixed: "left",
                  },
                  {
                    "prop": "id",
                    "width": 60,
                    "label": "序号"
                  },
                  {
                    "prop": "tudiquanshuren",
                    "label": "土地权属人",
                    "width": 0,
                    "align": "left"
                  },
                  {
                    "prop": "area",
                    "label": "区域",
                    "width": 0,
                    "align": "center"
                  },
                  {
                    "prop": "name",
                    "label": "地块名称",
                    "width": 0,
                    "align": "left",
                    "fixed": "left"
                  },
                  {
                    "prop": "tudizhenghao",
                    "label": "土地证号",
                    "width": 0,
                    "align": "left"
                  },
                  {
                    "prop": "zuoluo",
                    "label": "坐落",
                    "width": 0,
                    "align": "left"
                  },
                  {
                    "prop": "zichanweizhi",
                    "label": "资产位置",
                    "width": 0,
                    "align": "center"
                  },
                  {
                    "prop": "quanliren",
                    "label": "证载“权利人”",
                    "width": 0,
                    "align": "left"
                  },
                  {
                    "prop": "gongyouqingkuang",
                    "label": "共有情况",
                    "width": 0,
                    "align": "center"
                  },
                  {
                    "prop": "shiyongnianxian",
                    "label": "使用年限（年）",
                    "width": 0,
                    "align": "center"
                  },
                  {
                    "prop": "xianzhuang",
                    "label": "现状",
                    "width": 0,
                    "align": "center"
                  },
                  {
                    "prop": "yongtu",
                    "label": "用途",
                    "width": 0,
                    "align": "left"
                  },
                  {
                    "prop": "shiyongquanleixing",
                    "label": "使用权类型",
                    "width": 0,
                    "align": "center"
                  },
                  {
                    "prop": "lingzhengriqi",
                    "label": "领证日期",
                    "width": 0,
                    "align": "center"
                  },
                  {
                    "prop": "zhongzhiriqi",
                    "label": "终止日期",
                    "width": 0,
                    "align": "center"
                  },
                  {
                    "prop": "dengjimianji",
                    "label": "登记面积（m²）",
                    "width": 0,
                    "align": "center"
                  },
                  {
                    "prop": "shijimianji",
                    "label": "实际面积（m²）",
                    "width": 0,
                    "align": "center"
                  },
                  {
                    "label": "不符情况",
                    "width": 0
                  },
                  {
                    "prop": "bufuyuanyin",
                    "label": "不符原因",
                    "width": 0,
                    "align": "center"
                  },
                  {
                    "prop": "ruzhangshijian",
                    "label": "入账时间",
                    "width": 0,
                    "align": "center"
                  },
                  {
                    "prop": "zhangmianyuanzhi",
                    "label": "账面原值",
                    "width": 0,
                    "align": "center"
                  },
                  {
                    "prop": "tudidengji",
                    "label": "土地等级",
                    "width": 0,
                    "align": "center"
                  },
                  {
                    "prop": "tudishuidanjia",
                    "label": "土地税单价",
                    "width": 0,
                    "align": "center"
                  },
                  {
                    "prop": "tudishui",
                    "label": "土地税",
                    "width": 0,
                    "align": "center"
                  },
                  {
                    "prop": "tudishuijiaonazhuti",
                    "label": "土地税缴纳主体",
                    "width": 0,
                    "align": "center"
                  },
                  {
                    "prop": "jiaoshuijine",
                    "label": "缴税金额",
                    "width": 0,
                    "align": "center"
                  }
                ]
              }
              action={this.index}
              req-opt={{
                table_name: "lands"
              }}
              on={{
                ['loaded']: _ => {
                  this.$nextTick(() => {
                    this.$refs['landLinkTable'].getListData()?.filter(item => this.originalForm.id_leases_to_assets_lease_id_relation.find(j => j.land_id === item.id))?.forEach(item => {
                      this.$refs['landLinkTable'].toggleRowSelection(item, true)
                    })
                    ++this.landSelectTemp;
                  })
                },
                ['select']: _ => ++this.landSelectTemp
              }}
            ></xy-table>
          </div>
        </el-drawer>

        <el-drawer title="房产列表"
                   visible={this.houseDialog}
                   size="64%"
                   on={{
                     ['update:visible']: (val) => this.houseDialog = val,
                   }}>
          <div style="padding: 0 10px;">
            <xy-table
              ref="houseLinkTable"
              table-item={
                [
                  {
                    type: "selection",
                    width: 56,
                    align: "center",
                    reserveSelection: true,
                    fixed: "left"
                  },
                  {
                    "prop": "id",
                    "width": 60,
                    "label": "序号"
                  },
                  {
                    "prop": "quanshuren",
                    "label": "权属人",
                    "width": 0,
                    "align": "center"
                  },
                  {
                    "prop": "area",
                    "label": "区域",
                    "width": 0,
                    "align": "center"
                  },
                  {
                    "prop": "name",
                    "label": "地块名称",
                    "width": 0,
                    "fixed": "left",
                    "align": "left"
                  },
                  {
                    "prop": "quanzhenghao",
                    "label": "权证号",
                    "width": 0,
                    "align": "center"
                  },
                  {
                    "prop": "zuoluo",
                    "label": "坐落",
                    "width": 0,
                    "align": "left"
                  },
                  {
                    "prop": "zichanweizhi",
                    "label": "房产位置",
                    "width": 0,
                    "align": "center"
                  },
                  {
                    "prop": "quanliren",
                    "label": "证载“权利人”",
                    "width": 0,
                    "align": "center"
                  },
                  {
                    "prop": "yongtu",
                    "label": "用途",
                    "width": 0,
                    "align": "left"
                  },
                  {
                    "prop": "zhuangtai",
                    "label": "现状",
                    "width": 0,
                    "align": "left"
                  },
                  {
                    "prop": "dengjishijian",
                    "label": "登记时间",
                    "width": 0,
                    "align": "center"
                  },
                  {
                    "prop": "dengjimianji",
                    "label": "登记面积（m²）",
                    "width": 0,
                    "align": "center"
                  },
                  {
                    "prop": "shijimianji",
                    "label": "实际面积（m²）",
                    "width": 0,
                    "align": "center"
                  },
                  {
                    "prop": "bufuyuanyin",
                    "label": "不符情况",
                    "width": 0,
                    "align": "center"
                  },
                  {
                    "prop": "ruzhangshijian",
                    "label": "入账时间",
                    "width": 0,
                    "align": "center"
                  },
                  {
                    "prop": "zhangmianyuanzhi",
                    "label": "账面原值",
                    "width": 0,
                    "align": "center"
                  },
                  {
                    "prop": "guanliantudizhengquanzheng",
                    "label": "关联土地证权证",
                    "width": 0,
                    "align": "center"
                  },
                  {
                    "prop": "shiyongzhuangtai",
                    "label": "使用状态",
                    "width": 0,
                    "align": "center"
                  }
                ]
              }
              action={this.index}
              req-opt={{
                table_name: "houses"
              }}
              on={{
                ['loaded']: _ => {
                  this.$nextTick(() => {
                    this.$refs['houseLinkTable'].getListData()?.filter(item => this.originalForm.id_leases_to_assets_lease_id_relation.find(j => j.house_id === item.id))?.forEach(item => {
                      this.$refs['houseLinkTable'].toggleRowSelection(item, true)
                    })
                    ++this.houseSelectTemp;
                  })
                },
                ['select']: _ => ++this.houseSelectTemp
              }}
            ></xy-table>
          </div>
        </el-drawer>
      </div>
    )
  },
  data() {
    return {
      houseDialog: false,
      houseSelectTemp: 0,
      landDialog: false,
      landSelectTemp: 0,

      columns: 1,
      row: {},
      formInfo: [],
      id: "",
      type: "add",
      dialogVisible: false,
      form: {},
      originalForm: {},
      rules: {},
      file: {},
    };
  },
  methods: {
    index,
    setRow (row) {
      this.row = row
    },
    init() {
      for (let key in this.form) {
        if (this.form[key] instanceof Array) {
          this.form[key] = [];
        } else {
          this.form[key] = "";
        }
      }
      this.$refs["elForm"].clearValidate();
    },
    show() {
      this.dialogVisible = true;
    },
    hidden() {
      this.dialogVisible = false;
    },
    setType(type = "add") {
      let types = ["add", "editor", "show"];
      if (types.includes(type)) {
        this.type = type;
      } else {
        console.warn("Unknown type: " + type);
      }
    },
    setId(id) {
      if (typeof id == "number") {
        this.id = id;
      } else {
        console.error("error typeof id: " + typeof id);
      }
    },

    async getDetail() {
      const res = await show({ id: this.id, table_name: 'leases' });
      this.$integrateData(this.form, res);

      this.formInfo.forEach((i) => {
        if (i.edit_input === "file") {

        }
        if (i.edit_input === "files") {
          this.file[i.field] = res[`${i.field}_upload_details`]
        }
      });
      this.form = Object.assign({}, this.form);
      this.originalForm = deepCopy(res);
    },

    submit() {
      if (/\/house/g.test(this.$route.path)) {
        this.form['house_id'] = this.row.id
      }
      if (/\/land/g.test(this.$route.path)) {
        this.form['land_id'] = this.row.id
      }
      if (this.type === "add") {
        if (this.form.hasOwnProperty("id")) {
          delete this.form.id;
        }
      }
      if (this.type === "editor") {
        Object.defineProperty(this.form, "id", {
          value: this.id,
          enumerable: true,
          configurable: true,
          writable: true,
        });
      }

      this.form.id_leases_to_assets_lease_id_relation = []
      this.$refs['houseLinkTable'].getSelection()?.forEach(i => {
        this.form.id_leases_to_assets_lease_id_relation.push({
          house_id: i.id,
          lease_id: this.id
        })
      })
      this.$refs['landLinkTable'].getSelection()?.forEach(i => {
        this.form.id_leases_to_assets_lease_id_relation.push({
          land_id: i.id,
          lease_id: this.id
        })
      })
      save(Object.assign(this.form, { table_name: 'leases' })).then(res => {
        this.$Message.success({
          content: `${this.type === "add" ? "新增" : "编辑"}成功`,
        });
        this.$emit("refresh");
        this.hidden();
      })
    },
  },
  computed: {
    title () {
      if (this.type === 'add') return '新增'
      if (this.type === 'editor') return '编辑'
      if (this.type === 'show') return '查看'
    },

    selectedLands () {
      let temp = this.landSelectTemp;
      return this.$refs['landLinkTable']?.getSelection() || [];
    },
    selectedHouses () {
      let temp = this.houseSelectTemp;
      return this.$refs['houseLinkTable']?.getSelection() || [];
    },
  },
  watch: {
    formInfo: {
      handler: function (newVal) {
        this.form = {};
        this.rules = {};
        this.file = {};
        newVal.forEach((i) => {
          if (i.field) {
            this.form[i.field] = "";
            if (
              i.validation instanceof Array &&
              i.validation.length > 0 &&
              !!i.validation.find((i) => i === "required")
            ) {
              this.rules[i.field] = [
                { required: true, message: `请填写${i.name}` },
              ];
            }
            if (i.edit_input === "files") {
              this.form[i.field] = [];
            }
            if (i.edit_input === "files" || i.edit_input === "file") {
              this.file[i.field] = [];
            }
            if (i.edit_input === "checkbox") {
              this.form[i.field] = [];
            }
            if (i._relations) {
              this.form[i._relations?.link_with_name] = [];
            }
          }
        });

        this.columns = newVal.length > 11 ? '2' : '1'
      },
      //immediate: true,
    },
    dialogVisible(val) {
      if (val) {
        document.documentElement.style.setProperty(
          "--column-num",
          this.columns
        );
        if (this.type === "editor" || this.type === "show") {
          this.$nextTick(() => this.getDetail());
        }
      } else {
        this.id = "";
        this.type = "";
        this.init();
        this.$refs["elForm"].clearValidate();
        delete this.form.id;
        for (let key in this.file) {
          this.file[key] = [];
        }
        this.$refs['landLinkTable'].clearSelection();
        this.$refs['houseLinkTable'].clearSelection();
      }
    },
  },
  created() {
    resolveFormInfo(15).then(res => this.formInfo = res)
  }
};
</script>

<style>
:root {
  --column-num: 2;
}
</style>
<style scoped lang="scss">
.uploaded-a {
  color: red;
  text-decoration: none;
  transition: all 0.2s;
}

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

.form-body {
  display: grid;
  grid-gap: 10px;
  grid-template-columns: repeat(var(--column-num), 1fr);
}
</style>
