<template>
  <div>
    <base-right-dialog
      size="1000px"
      ref="baseRightDialog"
      :footerShow="true"
      :dialogVisible.sync="dialogVisible"
      :title="dialogTitle + ' 集成前台任务'"
      @handleClose="handleDialogClose"
      :type="dialogType"
      :submitShow="submitShow"
      @handleConfirmClick="handleConfirmClick"
    >
      <base-form
        ref="basicsForm"
        :formRow="formRow"
        :isFunBtn="false"
        :rules="basicsRules"
        class="dialog_form"
        :spanWidth="`120px`"
        :loading="vLoading"

      >
        <template #plugName="{row}">
          <div>
            <baseNewSelect
              :lookflag="false"
              :ruleForm="row"
              :disabled="!submitShow"
              v-model="row['plugName']"
              @selectChangeHandle="selectChangeHandle"
            ></baseNewSelect>
          </div>
        </template>
      </base-form>
      <base-table
        :border="true"
        :showIndex="true"
        :tableColumn="tableVersionColumn"
        :tableData="tableVersionData"
        :funWidth="80"
        :funData="funData"
        @onFunc="onFunc"
      >
        <!--        编码-->
        <template v-slot:argName="{ row }">
          <div style="width: 100%">
            {{row.argName}}
          </div>
        </template>
        <template v-slot:argValue="{ row }">
          <div style="width: 100%">
            <!--            若参数类型为1 （字符串） 否则为2 （日期）-->
            <template v-if="row.argType==1">
              <template v-if="!submitShow">{{row.argValue}}</template>
              <el-input
                v-else
                v-model="row.argValue"
                clearable
                type="text"
                :disabled="!submitShow"
              ></el-input>
            </template>
<!--            日期选择器-->
            <template v-else-if="row.argType==2">
              <template v-if="!submitShow">{{row.startDate}}/{{row.endDate}}</template>
              <template v-else>
                <el-date-picker
                  v-model="row.startDate"
                  type="date"
                  placeholder="选择开始日期"
                  :disabled="!submitShow"
                  format="yyyy 年 MM 月 dd 日"
                  value-format="yyyy-MM-dd">
                </el-date-picker>
                <el-date-picker
                  v-model="row.endDate"
                  type="date"
                  placeholder="选择结束日期"
                  :disabled="!submitShow"
                  format="yyyy 年 MM 月 dd 日"
                  value-format="yyyy-MM-dd">
                </el-date-picker>
              </template>
            </template>
            <!--              年月-->
            <template v-else-if="row.argType==3">
              <template v-if="!submitShow">{{row.argValue}}</template>
              <template v-else>
                <el-date-picker
                  v-model="row.argValue"
                  type="month"
                  placeholder="年月"
                  :disabled="!submitShow"
                  format="yyyy 年 MM 月"
                  value-format="yyyy-MM">
                </el-date-picker>
              </template>
            </template>
            <!--              年月日-->
            <template v-else-if="row.argType==4">
              <template v-if="!submitShow">{{row.argValue}}</template>
              <template v-else>
                <el-date-picker
                  v-model="row.argValue"
                  type="date"
                  placeholder="年月日"
                  :disabled="!submitShow"
                  format="yyyy 年 MM 月 DD 日"
                  value-format="yyyy-MM-DD">
                </el-date-picker>
              </template>
            </template>
            <!--              年月日时间-->
            <template v-else-if="row.argType==5">
              <template v-if="!submitShow">{{row.argValue}}</template>
              <template v-else>
                <el-date-picker
                  v-model="row.argValue"
                  type="datetime"
                  placeholder="年月日时间"
                  :disabled="!submitShow">
                </el-date-picker>
              </template>
            </template>
          </div>
        </template>
        <template v-slot:argType="{ row }">
          <div style="width: 100%">
            <el-radio-group v-model="row.argType" :disabled="true">
              <el-radio label="1">字符串</el-radio>
              <el-radio label="2">日期</el-radio>
            </el-radio-group>
          </div>
        </template>
        <template v-slot:remark="{ row }">
          <div style="width: 100%">
            <template v-if="!submitShow">{{row.remark}}</template>
            <el-input
              v-else
              v-model="row.remark"
              clearable
              type="text"
              :disabled="!submitShow"
            ></el-input>
          </div>
        </template>
      </base-table>
      <template v-if="dialogTitle!=='新增'">
        <div class="small_title">操作记录</div>
        <base-table
          :border="true"
          :showIndex="true"
          :tableColumn="tableColumn"
          :tableData="tableData"
          :funWidth="80"
        >
        </base-table>
      </template>

    </base-right-dialog>
  </div>
</template>

<script>
import baseRightDialog from "@/components/base/baseRightDialog";
import baseNewSelect from "./baseNewSelect.vue"
import baseForm from "@/components/base/baseNewForm";
import baseTable from "@/components/base/baseTable";
import configData from "./configData";
import { authApi } from "@/api/apis/auth";
export default {
  components: {
    baseRightDialog,
    baseForm,
    baseTable,
    baseNewSelect
  },
  data() {
    return {
      dialogVisible: false,
      dialogTitle: "",
      dialogType: "",
      formRow: configData.formRow,
      basicsRules: configData.basicsRules,
      vLoading: false,
      newMarryOptions: [],
      submitShow: true,
      loadingType: true,
      tableVersionData: [],
      tableVersionColumn: configData.tableVersionColumn,
      funData: [],
      isEdit: false,
      select_dist:{},
      plugNameOptions:[],
      tableColumn:configData.operationTableColumn,//操作记录
      tableData:[],
    };
  },
  mounted() {
    this.initSelect()
  },
  methods: {
    // 插件下拉
    async initSelect(){
      let res = await authApi(
        "pluginService",
        "plugins",
        "queryPluginsByType",
        "",
        {
          "pluginType": "1"
        }
      );
      if(res.status == 200){
        console.log(res.attribute)
        res.attribute.forEach(item=>{
          this.$set(this.select_dist,item.pluginId,item)
        })
        this.formRow[0].elCol[0].options = res.attribute
      }
    },
    //下拉改变事件
    selectChangeHandle(val, options){
      if(!val){
        this.tableVersionData=[]
        return
      }
      //找到这条
      let obj = options.find(item=>{
        return item.plugName === val
      })
      console.log(obj)
      this.$set(this.$refs.basicsForm.ruleForm,'plugId',obj.plugId)
      this.$set(this.$refs.basicsForm.ruleForm,'plugName',obj.plugName)
      this.searchInfo(obj.plugId)
    },
    //下拉后查询单据详情
    async searchInfo(plugId){
      let params = {
        plugId
      };
      let res = await authApi(
        "sysPlugArgService",
        "integrationTaskService",
        "getPlugArgByPlugId",
        "",
        params
      );
      console.log(res,'res')
      if(res.status ==200){
        //数据处理
        let arr = []
        res.attribute.forEach(item=>{
          arr.push({
            startDate:"",
            endDate:"",
            remark:"",
            argValue:"",
            argName:item.argName,
            argCode:item.argCode,
            argType:item.argType,
          })

        })
        this.tableVersionData = arr
      }
    },
    openDialog(type, row) {
      this.queryProductClassfy();
      this.formRow = configData.formRow;
      this.submitShow = true;
      this.isEdit = false
      this.funData = []
      // 新增
      if (type == "add") {
        this.dialogTitle = "新增";
        this.dialogType = "add";
      }
      // 编辑
      if (type == "edit") {
        this.isEdit = true
        this.dialogTitle = "编辑";
        this.dialogType = "edit";
        this.productGetById(row.id);
      }
      // 查看
      if (type == "show") {
        this.funData = Object.assign([],[])
        this.submitShow = false;
        this.formRow = configData.formRowShow;
        this.dialogTitle = "查看";
        this.dialogType = "show";
        this.productGetById(row.id);

      }
      this.dialogVisible = true;
    },
    // 编辑详情
    async productGetById(id) {
      let params = {
        id: id,
      };
      let res = await authApi(
        "sysIntegratedForegroundTaskService",
        "integrationTaskService",
        "getIntegratedForegroundTask",
        "",
        params
      );
      if (res.status == "200") {
        this.$nextTick(() => {
          this.$refs.basicsForm.incomingParameters(res.attribute);
          this.tableVersionData=res.attribute.sysIntegratedForegroundTaskDetailEntityList
          this.tableVersionData.forEach(item=>{
            if(item.argType ==2){
              //日期处理
              this.$set(item,'startDate',item.argValue.split("/")[0])
              this.$set(item,'endDate',item.argValue.split("/")[1])
            }
          })
          this.tableData=res.attribute.sysIntegratedForegroundTaskParameterEntities
          // let result = [];
          // this.tableVersionData = Object.assign([], result);
        });
      }
    },
    addVersionDialog() {
      let obj = {
        argName:"",
        argCode:"",
        argType:"1",
        remark:"",
      };
      this.tableVersionData.push(obj);
    },
    // 删除
    onFunc(index, row) {
      if (index == 0) {
        this.$delConfirm().then(() => {
          this.tableVersionData.forEach((item, itemIndex) => {
            if (item.id === row.id) {
              this.tableVersionData.splice(itemIndex, 1);
            }
          });
        });
      }
    },
    // 弹窗关闭
    handleDialogClose() {
      this.tableVersionData = Object.assign([], []);
      this.$refs.basicsForm.resetFields();
      this.dialogVisible = false;
    },
    // 弹窗确认按钮
    handleConfirmClick() {
      this.$refs.basicsForm.$refs["ruleForm"].validate((valid) => {
        if (!valid) {
          return;
        } else {
          let flag = this.tableVersionData.some((item,index)=>{
            //日期特别处理 例：2024-12-13/2024-12-14
            if(item.argType ==2){
              //判断开始时间和结束时间
              let startDate = new Date(item.startDate); // 开始日期
              let endDate = new Date(item.endDate);   // 结束日期
              if(startDate > endDate){
                this.$vmNews(`第${index+1}行结束时间不能大于开始时间`)
                return true
              }
              this.$set(item,'argValue',item.startDate + "/" +item.endDate)
            }
          })
          if(flag) return
          let params = {
            ...this.$refs.basicsForm.ruleForm,
            sysIntegratedForegroundTaskDetailEntityList: this.tableVersionData,
          };
          if (this.dialogType == "add") {
            this.openLoading("submit");
            this.productSaveDto(params);
          }
          if (this.dialogType == "edit") {
            this.openLoading("submit");
            this.productUpdateDto(params);
          }
        }
      });
    },
    // 新增保存
    async productSaveDto(params) {
      let res = await authApi(
        "sysIntegratedForegroundTaskService",
        "integrationTaskService",
        "saveIntegratedForegroundTask",
        "",
        params
      );
      if (res.status == "200") {
        this.handleDialogClose();
        this.$vmNews("新增成功", "success");
        this.$emit("resetTable");
      }
    },
    // 编辑保存
    async productUpdateDto(params) {
      let res = await authApi(
        "sysIntegratedForegroundTaskService",
        "integrationTaskService",
        "updateIntegratedForegroundTask",
        "",
        params
      );
      if (res.status == "200") {
        this.handleDialogClose();
        this.$vmNews("更新成功", "success");
        this.$emit("resetTable");
      }
    },
    // 获取所有产品分类
    async queryProductClassfy() {
      let params = {
        tab_name: "sys_product",
        column_name: "classify",
      };
      let res = await authApi(
        "generalServiceImpl",
        "dictionaryshop",
        "selectDictionaryshop",
        "",
        params
      );
      if (res.status == "200") {
        this.formRow[1].elCol[0].options = res.attribute;
      }
    },
  },
};
</script>

<style scoped lang="scss">
.small_title{
  margin: 10px 0;
  font-size: 16px;
}
.dialogList {
  padding: 16px 0;
  border-top: 1px solid #dcdfe6;
  display: flex;
  flex-direction: column;
}

.updateBtn {
  border: 1px solid #ebedf1;
  padding: 5px 0;
  border-radius: 3px;
  text-align: center;
  font-size: 14px;
  cursor: pointer;
  width: 100px;
}

.updateBtn:hover {
  color: #1890ff;
  border-color: #badeff;
  background-color: #e8f4ff;
}

::v-deep .el-table__body-wrapper.is-scrolling-none {
  height: auto !important;
}

::v-deep .app-container {
  height: auto !important;
}
</style>
