<script>
import { save, show, index, destroy } from "@/api/system/baseForm";
import { CreateDialog } from "@/utils/createDialog";
import { deepCopy } from "@/utils";
export default {
  props: {
    formInfo: {
      type: Array,
      default: () => [],
    },
    tableName: String,
  },
  render(h) {
    let dialog = new CreateDialog(this, [
      {
        key: "tudiquanshuren",
        show: true,
        label: "请填写土地权属人",
        render: h('el-input', {
          attrs: {
            placeholder: "请填写土地权属人"
          },
          style: {
            width: '100%'
          },
          props: {
            size: 'small',
            value: this.form['tudiquanshuren'],
          },
          on: {
            input: e => {
              this.$set(this.form,'tudiquanshuren',e)
              this.$set(this.form,'tudishuijiaonazhuti',e)
              this.form = Object.assign({},this.form)
            }
          }
        })
      },
      {
        show: true,
        key: "tudishuidanjia",
        label: "土地税单价（元/平方米）",
        render: h('el-input', {
          attrs: {
            placeholder: "请填写土地税单价"
          },
          style: {
            width: '100%'
          },
          props: {
            size: 'small',
            value: this.form['tudishuidanjia'],
          },
          on: {
            input: e => {
              this.$set(this.form,'tudishuidanjia',e)
              if(!isNaN(Number(e)) && !isNaN(Number(this.form["shijimianji"]))) {
                this.$set(this.form,"tudishui",Number(e) * Number(this.form["shijimianji"]))
              }
            }
          }
        })
      },
      {
        show: true,
        key: "bufuyuanyin",
        label: "不符原因",
        render: h("el-input", {
          props: {
            disabled: this.form.dengjimianji === this.form.shijimianji,
            size: "small",
            value: this.form["bufuyuanyin"],
          },
          on: {
            input: e => {
              this.$set(this.form,'bufuyuanyin',e)
            }
          }
        }),
      },
      {
        show: true,
        key: "xianzhuang",
        label: "现状",
        render: h("div",[
          h('el-select',{
            props: {
              size: 'small',
              value: this.form.xianzhuang
            },
            style: {
              width: '100%'
            },
            on: {
              input: e => {
                this.$set(this.form,'xianzhuang',e)
              }
            }
          },this.formInfo?.find(i => i.field === 'xianzhuang')?._params?.map(i => h('el-option',{
            props: {
              label: i.key,
              value: i.value
            }
          }))),
          h('el-input',{
            style: {
              display: this.form.xianzhuang === '其他' ? 'block' : 'none',
              'margin-top': '6px'
            },
            attrs: {
              placeholder: "填写现状其他事项"
            },
            props: {
              value: this.xianzhuangInput,
              size: 'small',
            },
            on: {
              input: e => {
                this.$set(this,'xianzhuangInput',e)
              }
            }
          })
        ])
      },
      {
        key: "fangchanzhuangtai",
        label: "房产状态",
        render: h("el-input", {
          props: {
            readonly: true,
            size: "small",
            value: this.originalForm["id_house_properties_land_id_relation"]
              ? "房地权属合一"
              : "房地权属分离",
          },
        }),
      },
      {
        key: "house_relation",
        label: "关联房产",
        rowStyle: {
          "grid-column": "span 2",
        },
        render: h("xy-table", {
          ref: "houseTable",
          props: {
            list: this.type === 'add' ? [] : this.originalForm?.id_houses_land_id_relation,
            auths: [],
            reqOpt: {
              table_name: "houses",
            },
            tableItem: [
              // {
              //   type: "selection",
              //   reserveSelection: true,
              //   fixed: "left",
              //   width: 50,
              //   selectable: (row) => (!row.land_id || row.land_id === this.id),
              // },
              {
                label: "名称",
                prop: "name",
                minWidth: 160,
                fixed: "left",
              },
              {
                label: "区域",
                prop: "area",
                width: 80,
                formatter: (data, row, value) => {
                  let map = new Map([
                    [1, "宜兴市"],
                    [2, "惠山区"],
                    [3, "新吴区"],
                    [4, "梁溪区"],
                    [5, "江阴市"],
                    [6, "滨湖区"],
                    [7, "锡山区"],
                  ]);
                  return map.get(value);
                },
              },
              {
                label: "登记面积(m²)",
                prop: "dengjimianji",
                width: 120,
              },
              {
                label: "实际面积(m²)",
                prop: "shijimianji",
                width: 120,
              },
              {
                label: "入账时间",
                prop: "ruzhangshijian",
                width: 160,
              },
              {
                label: "账面原值",
                prop: "zhangmianyuanzhi",
                width: 160,
              },
            ],
          },
          on: {
            ["loaded"]: (_) => {
              //this.setCurrentRow();
              this.$refs["houseTable"].getListData()?.forEach(row => {
                if (row.land_id && row.land_id === this.id)  {
                  this.$refs["houseTable"].toggleRowSelection(row, true);
                }
              })
            },
            ["select"]: (selection, row) => {
              if (row.land_id && row.land_id !== this.id) {
                this.$message({
                  type: "warning",
                  message: "当前房产已有绑定土地",
                });
                this.$refs["houseTable"].toggleRowSelection(row, false);
                return;
              }
            },
            // ["row-click"]: ({ row }) => {
            //   if (row.land_id && row.land_id !== this.id) {
            //     this.$message({
            //       type: "warning",
            //       message: "当前房产已有绑定土地",
            //     });
            //     this.$refs["houseTable"].setCurrentRow();
            //     return;
            //   }
            //   this.form["ruzhangshijian"] = row.ruzhangshijian;
            //   this.form["zhangmianyuanzhi"] = row.zhangmianyuanzhi;
            //   this.pickHouseRow = deepCopy(row);
            //   delete this.pickHouseRow.id_his_evolutions_house_id_relation;
            //   let copyRow = deepCopy(row);
            //   delete copyRow.id;
            //   copyRow.land_id = this.id;
            //   this.form["id_house_properties_land_id_relation"] = [
            //     Object.assign(
            //       this.originalForm?.id_house_properties_land_id_relation
            //         ? this.originalForm.id_house_properties_land_id_relation
            //         : {},
            //       copyRow
            //     ),
            //   ];
            // },
          },
        }),
      },
    ],{
      width: "80vw"
    });
    return dialog.render();
  },
  data() {
    return {
      columns: 1,
      id: "",
      type: "add",
      dialogVisible: false,
      form: {},
      originalForm: {},
      rules: {},
      file: {},

      pickHouseRow: null,
      xianzhuangInput: ""
    };
  },
  methods: {
    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"];
      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: this.tableName });
      this.$integrateData(this.form, res);

      this.formInfo.forEach((i) => {
        if (i && (i.edit_input === "file" || i.edit_input === "files")) {
          res[i._relations.link_with_name]
            ? (this.file[i.field] =
                res[i._relations.link_with_name] instanceof Array
                  ? res[i._relations.link_with_name].map((i) => {
                      return {
                        name: i?.original_name || i?.name,
                        url: i?.url,
                        response: i,
                      };
                    })
                  : [
                      {
                        name: res[i._relations.link_with_name]?.name,
                        url: res[i._relations.link_with_name]?.url,
                        response: res[i._relations.link_with_name],
                      },
                    ])
            : (this.file[i.field] = []);
        }

        this.form = Object.assign({}, this.form);
        this.originalForm = deepCopy(res);
      });

      this.$refs['houseTable'].getListData().forEach(row => {
        if (this.originalForm.id_houses_land_id_relation.find(i => i.id === row.id)) {
          this.$refs['houseTable'].toggleRowSelection(row, true);
        }
      })
    },

    submit() {
      let promiseAll = [];
      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.$refs["elForm"].validate((validate) => {
        if (validate) {
          let copyForm = deepCopy(this.form);
          if(copyForm.xianzhuang === '其他') {
            copyForm.xianzhuang = this.xianzhuangInput
          }
          this.formInfo.forEach((info) => {
            if (
              info._relations?.link_relation === "newHasMany" ||
              info._relations?.link_relation === "hasMany"
            ) {
              if (this.originalForm[info._relations.link_with_name]) {
                this.originalForm[info._relations.link_with_name].map((i) => {
                  promiseAll.push(
                    destroy({
                      id: i.id,
                      table_name: info._relations.link_table_name,
                    })
                  );
                });
              }
            }

            if (copyForm[info._relations?.link_with_name]?.length > 0) {
              delete copyForm[info.field];
            }
            if (
              info._relations?.link_relation === "newHasMany" ||
              info._relations?.link_relation === "hasMany"
            ) {
              if (info.edit_input === "files") {
                copyForm[info._relations.link_with_name] = this.file[
                  info.field
                ]?.map((i) => {
                  let copyRelation = i?.response ? deepCopy(i?.response) : "";
                  delete copyRelation.id;
                  return {
                    upload_id: i?.response?.id,
                    ...copyRelation,
                  };
                });
              } else {
                copyForm[info._relations.link_with_name] = copyForm[
                  info.field
                ]?.map((i) => {
                  let copyRelation = info._params.find(
                    (param) => param[info._relations?.foreign_key] === i
                  )
                    ? deepCopy(
                        info._params.find(
                          (param) => param[info._relations?.foreign_key] === i
                        )
                      )
                    : "";
                  delete copyRelation.id;
                  return {
                    [info._relations.foreign_key]: i,
                    ...copyRelation,
                  };
                });
              }

              delete copyForm[info.field];
            }
            if (
              info._relations?.link_relation === "newHasOne" ||
              info._relations?.link_relation === "hasOne"
            ) {
              if (info.edit_input === "file") {
                copyForm[info._relations.link_with_name] = [
                  {
                    upload_id: this.file[info.field]?.response?.id,
                    ...this.file[info.field],
                  },
                ];
              } else {
                let copyRelation = deepCopy(
                  info._params.find(
                    (param) => param.id == this.form[info.field]
                  )
                );
                if (copyRelation) {
                  delete copyRelation.id;
                  copyForm[info._relations.link_with_name] = [
                    {
                      id: this.form[info._relations?.link_with_name]?.id,
                      [info.field === "shenhebumen"
                        ? "dept_id"
                        : info._relations.foreign_key]: this.form[info.field],
                      ...copyRelation,
                    },
                  ];
                }
              }

              delete copyForm[info.field];
            }
            if (!copyForm[info._relations?.link_with_name]) {
              delete copyForm[info._relations?.link_with_name];
            }
          });
          // if (this.$refs["houseTable"].getSelection() && this.$refs["houseTable"]?.getSelection()?.length > 0) {
          //   promiseAll.push(
          //     ...this.$refs["houseTable"].getSelection().map(i => {
          //       for (let key in i) {
          //         if (/_relation/g.test(key)) {
          //           delete i[key]
          //         }
          //       }
          //       return save(Object.assign(i, { table_name: 'houses',land_id: this.id, quanzhenghao: copyForm.tudizhenghao, zichanweizhi: copyForm.zichanweizhi }))
          //     })
          //   );
          // }
          // this.originalForm.id_houses_land_id_relation.forEach(item => {
          //   if (this.$refs["houseTable"].getSelection().findIndex(selected => selected.id === item.id) === -1) {
          //     promiseAll.push(
          //       save(Object.assign(item, { table_name: 'houses',land_id: "" }))
          //     );
          //   }
          // })
          promiseAll.push(
            save(Object.assign(copyForm, { table_name: this.tableName }))
          );
          Promise.all(promiseAll).then((res) => {
            this.$Message.success({
              content: `${this.type === "add" ? "新增" : "编辑"}成功`,
            });
            this.$emit("refresh");
            this.hidden();
          });
        }
      });
    },

    setCurrentRow() {
      this.$nextTick(() => {
        this.$refs["houseTable"].setCurrentRow(
          this.$refs["houseTable"]
            .getListData()
            .find((row) => row.land_id === this.id)
        );
      });
    },
  },
  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.field === 'bufuyuanyin') {
              this.rules[i.field] = [
                { validator: (rule, value, callback) => {
                    if (this.form.dengjimianji === this.form.shijimianji) {
                      callback()
                    } else {
                      if (!value) {
                        callback(new Error('登记面积与实际面积不符，请填写不符原因'))
                      } else {
                        callback()
                      }
                    }
                  } },
              ];
            }
            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 = "2";
      },
      //immediate: true,
    },
    dialogVisible(val) {
      if (val) {
        document.documentElement.style.setProperty(
          "--column-num",
          this.columns
        );
        if (this.type === "editor") {
          this.$nextTick(() => this.getDetail());
        }
      } else {
        this.id = "";
        this.type = "";
        this.init();
        this.$refs["elForm"].clearValidate();
        this.$refs["houseTable"].getTableData(true);
        this.$refs["houseTable"].clearSelection();
        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: $primaryColor;
  text-decoration: none;
  transition: all 0.2s;
}

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

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