<template>
  <div class="app-container">
    <el-card>
      <h2 style="margin-bottom: 20px">创建推送任务</h2>
      <el-form :model="form" ref="form" label-width="120px" :rules="rules">
        <el-form-item label="任务名称" prop="manageRouteName">
          <el-input
            v-model="form.manageRouteName"
            placeholder="请输入任务名称"
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item label="指定时间" prop="nodePlanTime">
          <el-date-picker
            v-model="form.nodePlanTime"
            type="datetime"
            value-format="yyyy-MM-dd HH:mm:ss"
            placeholder="请选择指定时间"
            :picker-options="pickerOptions"
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item label="任务节点类型" prop="batchTaskSource">
          <el-radio-group v-model="form.batchTaskSource">
            <el-radio label="telephone">电话外呼</el-radio>
            <el-radio label="message">短信推送</el-radio>
          </el-radio-group>
        </el-form-item>

        <!-- 电话外呼部分 -->
        <template v-if="form.batchTaskSource === 'telephone'">
          <el-form-item label="话术模板" prop="phoneTemplate">
            <scripts
              @on-template="handlePhoneTemplateSelect"
              :templateId="form.phoneTemplateId"
              :node="form.phoneDialMethod"
              :templateName="form.phoneTemplate"
            ></scripts>
          </el-form-item>
          <el-form-item label="话术简介" prop="phoneDesc">
            <el-input
              v-model="form.phoneNodeContent"
              type="textarea"
              placeholder="话术简介"
              autosize
              disabled
            />
          </el-form-item>
          <!-- <el-form-item label="话术变量" prop="phoneVars">
            <el-input
              v-model="form.phoneVars"
              type="textarea"
              placeholder="请输入话术变量（如有多个请用逗号分隔）"
            />
          </el-form-item> -->
          <el-form-item label="重播次数" prop="phoneRedialTimes">
            <el-select v-model="form.phoneRedialTimes" style="width: 200px">
              <el-option
                v-for="item in optionslisttime"
                :key="item.dictValue"
                :label="item.dictLabel"
                :value="item.dictValue"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="时间间隔(分)" prop="phoneTimeInterval">
            <el-input
              v-model.number="form.phoneTimeInterval"
              oninput="value=value.replace(/[^\d]/g,'')"
              style="width: 200px"
            />
          </el-form-item>
        </template>

        <!-- 短信推送部分 -->
        <template v-if="form.batchTaskSource === 'message'">
          <el-form-item label="短信模板" prop="smsTemplate">
            <message
              @on-template="handleSmsTemplateSelect"
              :templateId="form.smsTemplateId"
              :templateName="form.smsTemplate"
            ></message>
          </el-form-item>
          <el-form-item label="短信简介" prop="messageNodeContent">
            <el-input
              v-model="form.messageNodeContent"
              type="textarea"
              placeholder="短信简介"
              autosize
              disabled
            />
          </el-form-item>
          <el-form-item label="短信变量" v-if="smsVarsVisible">
            <div
              style="
                display: flex;
                gap: 12px;
                align-items: center;
                flex-wrap: wrap;
              "
            >
              <div
                v-for="key in smsVarKeys"
                :key="key"
                style="display: flex; align-items: center; gap: 8px"
              >
                <el-form-item :label="key">
                  <el-input
                    v-model="form.vars[key]"
                    :placeholder="'请输入' + key"
                    style="width: 200px"
                  />
                </el-form-item>
              </div>
            </div>
          </el-form-item>
        </template>

        <el-form-item>
          <el-button type="primary" @click="handleSubmit">保存</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import scripts from "../components/script.vue";
import message from "../components/message.vue";
import { getAgencytype } from "@/api/system/agency";
import {
  AllBatchSendTaskInfo,
  generatePushTask,
} from "@/api/system/batchSendTaskInfo";

export default {
  name: "CreatePushTask",
  components: { scripts, message },
  data() {
    return {
      rules: {
        manageRouteName: [
          { required: true, message: "任务名称不能为空", trigger: "blur" },
        ],
        nodePlanTime: [
          { required: true, message: "指定时间不能为空", trigger: "change" },
        ],
        batchTaskSource: [
          {
            required: true,
            message: "任务节点类型不能为空",
            trigger: "change",
          },
        ],
      },
      pickerOptions: {
        disabledDate(time) {
          return time.getTime() < Date.now() - 8.64e7;
        },
      },
      optionslisttime: [],
      smsVarsVisible: false,
      smsVarKeys: [],
      form: {
        manageRouteName: "",
        nodePlanTime: "",
        batchTaskSource: "",
        phoneDialMethod: "AI",
        phoneTemplateId: "",
        phoneTemplate: "",
        phoneNodeContent: "",
        scriptInfoId: "",
        robotPublishId: "",
        phoneTemplateName: "",
        phoneDesc: "",
        phoneVars: "",
        phoneRedialTimes: "",
        phoneTimeInterval: "",
        smsTemplateId: "",
        smsTemplate: "",
        messageTemplateId: "",
        messageTemplateCode: "",
        messageTemplateName: "",
        messageNodeContent: "",
        physicalExaminationLabel: "",
        vars: {},
        list: [],
      },
    };
  },
  created() {
    this.infolistMESSAGE();
    this.form.physicalExaminationLabel =
      this.$route.query.physicalExaminationLabel || "";
    AllBatchSendTaskInfo(this.$route.query).then((res) => {
      this.form.list = res || [];
    });
  },
  mounted() {},
  methods: {
    infolistMESSAGE() {
      const dictType = "redial_times";
      getAgencytype(dictType).then((res) => {
        this.optionslisttime = res.data || [];
      });
    },
    handlePhoneTemplateSelect(item) {
      this.form.phoneTemplateId = item.phoneTemplateId || "";
      this.form.phoneTemplate = item.templateName || "";
      this.form.phoneNodeContent = item.templateContent || "";
      this.form.robotPublishId = item.robotPublishId || "";
      this.form.phoneTemplateName = item.templateName || "";
      this.form.scriptInfoId = item.scriptInfoId || "";
    },
    handleSmsTemplateSelect(item) {
      this.form.smsTemplateId = item.templateId || "";
      this.form.smsTemplate = item.templateName || "";
      this.form.messageTemplateId = item.templateId || "";
      this.form.messageTemplateCode = item.messageTemplateCode || "";
      this.form.messageTemplateName = item.templateName || "";
      this.form.messageNodeContent = item.templateContent || "";
      const variablesStr = item.variables;
      if (variablesStr && String(variablesStr).trim() !== "") {
        const keys = String(variablesStr)
          .split("|")
          .map((s) => s.trim())
          .filter(Boolean);

        this.smsVarsVisible = keys.length > 0;
        this.smsVarKeys = keys;

        const keySet = new Set(keys);

        // 写入模板变量占位符（例如 month|day）
        keys.forEach((key) => {
          if (this.form.vars[key] === undefined)
            this.$set(this.form.vars, key, "");
        });

        // 清理不在模板变量里的旧值，避免沿用旧模板变量
        Object.keys(this.form.vars).forEach((existingKey) => {
          if (!keySet.has(existingKey))
            this.$delete(this.form.vars, existingKey);
        });
      } else {
        this.smsVarsVisible = false;
        this.smsVarKeys = [];
        Object.keys(this.form.vars).forEach((existingKey) => {
          this.$delete(this.form.vars, existingKey);
        });
      }
    },
    handleSubmit() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          if (
            this.form.batchTaskSource == "message" &&
            !this.form.messageTemplateName
          ) {
            this.$message.error("请选择短信模板");
            return;
          }
          if (
            this.form.batchTaskSource == "telephone" &&
            !this.form.phoneTemplateName
          ) {
            this.$message.error("请选择话术模板");
            return;
          }
          const loading = this.$loading({
            lock: true,
            text: "加载中",
            spinner: "el-icon-loading",
            background: "rgba(0, 0, 0, 0.7)",
          });
          generatePushTask(this.form).then((res) => {
            loading.close();
            if (res.code == 200) {
              this.$message.success(res.msg);
            }
          });
        }
      });
    },
  },
};
</script>

<style scoped>
.app-container {
  padding: 24px;
}

::v-deep .el-form-item__label {
  font-size: 16px !important;
}
.el-textarea {
  font-size: 16px;
}
</style>
