<script>
import { save, show, index, destroy } from "@/api/system/baseForm";
import { CreateDialog } from "@/utils/createDialog"
import { deepCopy } from "@/utils";
import { resolveFormInfo } from '@/utils/createTable';
import { sendSms } from "@/api/other"
export default {
  props: {
    tableName: String,
  },
  render(h) {
    let dialog = new CreateDialog(this,[
      {
        key: "telephone_group",
        label: "通知号码组",
        render: row => {
          return (
            <el-select style="width: 100%;"
                       vModel={this.groupId}
                       value-key="id"
                       clearable={true}
                       on={{
                         ['change']:e => {
                           this.smsForm.mobile = e.id_telephone_group_relations_group_id_relation?.map(i => i.name)}
                       }}>
              {
                this.telephoneGroups.map(i =>
                  (
                    <el-option value={i} label={i.name}>
                      <span style="float: left">{i.name}</span>
                      <span style="text-align: right;float: right;width: 50%;overflow: hidden;text-overflow: ellipsis;white-space: nowrap;">
                        {
                          i.id_telephone_group_relations_group_id_relation?.map((j, ji) => (j.name + ( ji === i.id_telephone_group_relations_group_id_relation.length - 1 ? '' : ',' )))
                        }
                      </span>
                    </el-option>
                  )
                )
              }
            </el-select>
          )
        }
      }
    ],{
      width: "650px"
    })
    return dialog.render()
  },
  data() {
    return {
      columns: 1,
      row: {},
      formInfo: [],
      id: "",
      transfer_id: '',
      type: "add",
      dialogVisible: false,
      form: {},
      originalForm: {},
      rules: {},
      file: {},

      telephoneGroups: [],
      groupId: '',
      smsForm: {
        mobile: [],
        content: ""
      }
    };
  },
  methods: {
    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.transfer_id = id;
      } else {
        console.error("error typeof id: " + typeof id);
      }
    },

    async getDetail() {
      const res = await show({ id: this.id, table_name: 'feedbacks' });
      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?.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);
      });
    },

    submit() {
      this.smsForm.content = `调令平台反馈：${ this.$moment().format('YYYY-MM-DD HH:mm') }，${ this.row.equipment_id_equipments_id_relation.name }，关于${ this.form.content }指令有误，申请${ this.$refs['elEdit_type']?.selectedLabel || '' }`
      if (this.type === "add") {
        this.form.transfer_id = this.transfer_id;
        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.status = 1;
      save(Object.assign(this.form, { table_name: 'feedbacks' })).then(res => {
        this.$Message.success({
          content: `${this.type === "add" ? "新增" : "编辑"}成功`,
        });
        this.$emit("refresh");
        this.hidden();

        if (this.smsForm.mobile && this.smsForm.mobile.length > 0 && this.smsForm.content) {
          sendSms(this.smsForm)
        }
      })
    },

    async getTelephoneGroups () {
      this.telephoneGroups = (await index({
        table_name: "groups",
        page: 1,
        page_size: 999
      })).data
    }
  },
  computed: {
    title () {
      if (this.type === 'add') return '新增'
      if (this.type === 'editor') return '编辑'
      if (this.type === 'show') return '查看'
    }
  },
  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] = [];
        }
      }
    },
  },
  created() {
    this.getTelephoneGroups()
    resolveFormInfo(5,'form').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>
