<script>
import { save, show, index, destroy, imports } from "@/api/system/baseForm";
import { CreateDialog } from "@/utils/createDialog"
import { deepCopy } from "@/utils";
import { resolveFormInfo } from '@/utils/createTable'
export default {
  components: {
  },
  props: {
    tableName: String,
  },
  render(h) {
    const _this = this;
    let dialog = new CreateDialog(this,[
    ],{}, false)

    return (
      <div>
        <el-card style="margin-top: 20px;">
          <div slot="header" style="display: flex;align-items: center;">
            <i class="el-icon-back"
               style="padding-right: 20px;font-size: 20px;font-weight: 600;cursor: pointer;"
               on={{
                 ['click']: _ => {
                   this.$router.go(-1)
                 }
               }}></i>
            <p>{ (() => {
              let title = new Map([
                ['add', '新增招租'],
                ['editor', '编辑招租']
              ])
              return title.get(this.type)
            })() }</p>
          </div>

          {/* 资产信息 */}
          <div style="margin-bottom: 10px;">
            <div style="display: flex;margin-bottom: 10px;align-items: center;">
              <p style="font-weight: 700;line-height: 2;">资产信息</p>

              <div style="margin-left: auto;">
                <Button type="primary"
                        shape="circle"
                        on={{
                          ['click']: _ => {
                            this.landDialog = true;
                          }
                        }}>选择土地</Button>
                <Button type="primary"
                        shape="circle"
                        on={{
                          ['click']: _ => {
                            this.houseDialog = true;
                          }
                        }}>选择房产</Button>
              </div>
            </div>

            <xy-table
              row-key={
                row => {
                  row._relation_id ? row._relation_id : (row.hasOwnProperty('land_id') ? 'house_' + row.id : 'land_' + row.id)
                }
              }
              ref="assetsTable"
              list={this.nowAssets}
                      height="300"
                      isHandlerKey={false}
                      is-page={false}
                      table-item={
                        [
                          {
                            "prop": "name",
                            "label": "地块名称",
                            "width": 0,
                            "fixed": "left",
                            "align": "left"
                          },
                          {
                            "prop": "zuoluo",
                            "label": "坐落",
                            "width": 0,
                            "align": "left"
                          },
                          {
                            "prop": "dengjimianji",
                            "label": "登记面积（m²）",
                            "width": 0,
                            "align": "center"
                          },
                          {
                            "prop": "_chuzumianji",
                            "label": "出租面积（m²）",
                            "width": 160,
                            customFn: row => {
                              return (
                                <el-input-number controls={false} precision={2} vModel={row._chuzumianji} size="small"></el-input-number>
                              )
                            }
                          },
                          {
                            prop: "operate",
                            label: "操作",
                            width: 160,
                            customFn: row => {
                              return (
                                <div style="display: flex;">
                                  <Button type="error"
                                          size="small"
                                          ghost={true}
                                          on={{
                                            ['click']: _ => {
                                              this.$confirm("确定删除？").then(_ => {
                                                if (row.hasOwnProperty("land_id")) {
                                                  this.$refs["houseLinkTable"]?.toggleRowSelection(
                                                    this.$refs["houseLinkTable"].getListData().find(i => i.id === row.id)
                                                    ,false)

                                                } else {
                                                  this.$refs["landLinkTable"]?.toggleRowSelection(
                                                    this.$refs["landLinkTable"].getListData().find(i => i.id === row.id)
                                                    ,false)
                                                }

                                                if (row._relation_id) {
                                                  destroy({ table_name: "lets_to_assets", id: row._relation_id },false).then(_ => {
                                                    this.nowAssets.splice(this.nowAssets.findIndex(j => j._relation_id === row._relation_id),1)
                                                  })
                                                }
                                              })
                                            }
                                          }}>删除</Button>
                                </div>
                              )
                            }
                          }
                        ]
                      }></xy-table>
          </div>

          {
            dialog.render()
          }
        </el-card>

        <el-drawer title="土地列表"
                   visible={this.landDialog}
                   size="64%"
                   on={{
                     ['update:visible']: (val) => this.landDialog = val,
                   }}>
          <div style="padding: 0 10px;">
            <div>
              <Input vModel={this.landSelect.keyword} style="width: 300px;"  placeholder="请填写关键词"/>
              <Button type="primary"
                      style="margin-left: 10px;"
                      on={{
                        ['click']: _ => {
                          this.$refs['landLinkTable'].getTableData(true)
                        }
                      }}>搜索</Button>
            </div>
            <xy-table
              isHandlerKey={false}
              height="600"
              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={this.landSelect}
              on={{
                ['loaded']: _ => {
                  this.$nextTick(() => {
                    this.$refs['landLinkTable'].getListData()?.filter(item => this.nowAssets?.find(j => j.id === item.id && !j.hasOwnProperty('land_id')))?.forEach(item => {
                      this.$refs['landLinkTable'].toggleRowSelection(item, true)
                    })
                  })
                },
                ['select']: (selection, row) => {
                  if (selection.find(i => i.id === row.id)) {
                    this.nowAssets.push({
                      id: row.id,
                      name: row.name,
                      zuoluo: row.zuoluo,
                      zichanweizhi: row.zichanweizhi,
                      dengjimianji: row.dengjimianji,
                      _chuzumianji: 0,
                      _relation_id: "",
                    })
                  } else {
                    let index = this.nowAssets.findIndex(i => i.id === row.id && !i.hasOwnProperty('land_id') )
                    let temp = this.nowAssets.splice(index, 1)
                    if (temp._relation_id) {
                      destroy({
                        table_name: "lets_to_assets",
                        id: temp._relation_id
                      },false)
                    }
                  }
                }
              }}
            ></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;">
            <div>
              <Input vModel={this.houseSelect.keyword} style="width: 300px;" placeholder="请填写关键词"/>
              <Button type="primary"
                      style="margin-left: 10px;"
                      on={{
                        ['click']: _ => {
                          this.$refs['houseLinkTable'].getTableData(true)
                        }
                      }}>搜索</Button>
            </div>
            <xy-table
              isHandlerKey={false}
              height="600"
              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={this.houseSelect}
              on={{
                ['loaded']: _ => {
                  this.$nextTick(() => {
                    this.$refs['houseLinkTable'].getListData()?.filter(item => this.nowAssets?.find(j => j.id === item.id && j.hasOwnProperty('land_id')))?.forEach(item => {
                      this.$refs['houseLinkTable'].toggleRowSelection(item, true)
                    })
                  })
                },
                ['select']: (selection, row) => {
                  if (selection.find(i => i.id === row.id)) {
                    this.nowAssets.push({
                      id: row.id,
                      name: row.name,
                      zuoluo: row.zuoluo,
                      zichanweizhi: row.zichanweizhi,
                      dengjimianji: row.dengjimianji,
                      _chuzumianji: 0,
                      _relation_id: "",
                      land_id: row.land_id
                    })
                  } else {
                    let index = this.nowAssets.findIndex(i => i.id === row.id && i.hasOwnProperty('land_id') )
                    let temp = this.nowAssets.splice(index, 1)
                    if (temp._relation_id) {
                      destroy({
                        table_name: "lets_to_assets",
                        id: temp._relation_id
                      },false)
                    }
                  }
                }
              }}
            ></xy-table>
          </div>
        </el-drawer>

      </div>
    )
  },
  data() {
    return {
      nowAssets: [],
      houseDialog: false,
      landDialog: false,
      leasePlans: [],
      landSelect: {
        table_name: "lands",
        keyword: ""
      },
      houseSelect: {
        table_name: "houses",
        keyword: ""
      },

      columns: 1,
      row: {},
      formInfo: [],
      id: "",
      type: "add",
      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();
    },
    setType(type = "add") {
      let types = ["add", "editor"];
      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: 'lets' });
      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);
      this.originalForm?.lets_to_assets?.forEach(item => {
        if (item.land_id) {
          let land = item.lands;
          if (land) {
            this.nowAssets.push({
              id: land.id,
              name: land.name,
              zuoluo: land.zuoluo,
              zichanweizhi: land.zichanweizhi,
              dengjimianji: land.dengjimianji,
              _chuzumianji: item.chuzumianji||0,
              _relation_id: item.id,
            });
          }
        } else {
          let house = item.house;
          if (house) {
            this.nowAssets.push({
              id: house.id,
              name: house.name,
              zuoluo: house.zuoluo,
              zichanweizhi: house.zichanweizhi,
              dengjimianji: house.dengjimianji,
              _chuzumianji: item.chuzumianji||0,
              _relation_id: item.id,
              land_id: house.land_id,
            });
          }
        }
        })
    },

    submit() {
      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.selectedHouses?.forEach(i => {
      //   this.form.id_leases_to_assets_lease_id_relation.push({
      //     house_id: i.id,
      //     lease_id: this.id,
      //     chuzumianji: i._chuzumianji
      //   })
      // })
      // this.selectedLands?.forEach(i => {
      //   this.form.id_leases_to_assets_lease_id_relation.push({
      //     land_id: i.id,
      //     lease_id: this.id,
      //     chuzumianji: i._chuzumianji
      //   })
      // })
      // this.form.id_lease_plans_lease_id_relation = this.leasePlans;
      save(Object.assign(this.form, { table_name: 'lets' })).then(res => {
        Promise.all(this.originalForm.id_lets_to_assets_let_id_relation?.map(i => destroy({
          id: i.id,
          table_name: "lets_to_assets"
        },false)))
        let leaseToAssetsData = this.nowAssets.map(item => ({
          id: item._relation_id,
          land_id: !item.hasOwnProperty("land_id") ? item.id : "",
          house_id: item.hasOwnProperty("land_id") ? item.id : "",
          chuzumianji: item._chuzumianji,
          let_id: res.id
        }));
        if (leaseToAssetsData && leaseToAssetsData.length > 0) {
          imports({
            table_name: "lets_to_assets",
            data: leaseToAssetsData
          },false)
        }
        this.$Message.success({
          content: `${this.type === "add" ? "新增" : "编辑"}成功`,
        });
        this.$emit("refresh");
        this.$router.back();
      })
    },
  },
  computed: {

  },
  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 === "change") {
          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() {
    this.id = this.$route.query.letId;
    this.type = this.$route.query.type;
    resolveFormInfo(31).then(res => {
      this.formInfo = res;

      if (this.type === "editor" || this.type === "change") {
        this.$nextTick(() => this.getDetail());
      }
    })
  },
  mounted() {

  },
  beforeDestroy() {
    this.id = "";
    this.type = "";
    this.init();
    this.$refs["elForm"].clearValidate();
    delete this.form.id;
    for (let key in this.file) {
      this.file[key] = [];
    }
  }
};
</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);
}
::v-deep .el-input-number input {
  text-align: right;
}
</style>
