<script>
import useColumns from "./columns";
import {
  addTargetTemplate,
  updateTargetTemplate,
  getTargetTemplate,
  checkQuote,
} from "@/api/business/spd/starget/targetTemplate";
export default {
  name: "AddDrawer",
  props: {
    dict: {
      type: Object,
    },
    selectData: {
      type: Object,
      require: true,
    },
    addType: {
      type: String,
      default: "add",
    },
  },
  components: {
    ElSuperForm: () => import("@/components/super-form/index.vue"),
    ElSuperTable: () => import("@/components/super-table/index.vue"),
    ElPopoverSelectV2: () => import("@/components/popover-select-v2/index.vue"),
  },
  data() {
    const {
      TabColumns,
      TableColumns,
      TabColumns: [
        {
          item: { key: tabName },
        },
      ],
    } = useColumns();
    const rules = this.$init.rules([...TabColumns, ...TableColumns]);
    const params = this.$init.params([...TabColumns, ...TableColumns]);
    return {
      width: "100%",
      visible: false,
      loading: false,
      rules: rules,
      params: params,
      tabName: tabName,
      TabColumns: TabColumns,
      TableColumns: TableColumns,
    };
  },
  computed: {
    title: {
      get() {
        const { addType } = this;
        if (addType === "add") {
          return "新 增";
        }
        if (addType === "edit") {
          return "编 辑";
        }
      },
      set() {},
    },
  },
  watch: {},
  methods: {
    changePuOrgName(prop) {
      console.log("changePuOrgName", prop);
    },
    changeMaterialName(prop) {
      console.log("changeMaterialName", prop);
    },

    //查询目标模板详情
    async fetchTemplate(prop) {
      try {
        // try
        this.loading = true;
        const { code, data } = await getTargetTemplate(prop);
        if (code === 200) {
          this.params = data;
          return true;
        } else {
          return false;
        }
      } catch (err) {
        // catch
        console.error(err);
      } finally {
        // finally
        this.loading = false;
      }
    },
    //打开组件
    async open() {
      const { addType, selectData } = this.$props;
      if (addType === "add") {
        this.visible = true;
        var date = new Date();
        this.params.year = date.getFullYear() + '-' + '01' + '-' + '01';
        this.params.startTime = date.getFullYear() + '-' + '01' + '-' + '01';
        this.params.deadlineTime = date.getFullYear() + '-' + '12' + '-' + '31';
        this.params.cycle = 'month';
      }
      if (addType === "edit") {
        //校验目标模板是否存在引用
        const { code, data } = await checkQuote(selectData.id);
        if (code == "200") {
          if (data) {
            this.$modal.msgError("该目标模板存在引用，无法修改！");
            this.visible = false;
            return;
          }
        } else {
          this.$modal.msgError("校验该目标模板是否存在引用异常，无法修改！");
          this.visible = false;
          return;
        }
        this.visible = await this.fetchTemplate(selectData.id);
        this.params.indexs = this.params.indexs.map((item) => ({ ...item}));
        this.params.dimensionalitys = this.params.dimensionalitys.map(
          (item) => ({ ...item})
        );
        this.params.cycles = this.params.cycles.map((item) => ({ ...item}));
        console.log("this.params",this.params);
      }
    },
    //关闭页面
    async hide() {
      const {
        TabColumns,
        TableColumns,
        TabColumns: [
          {
            item: { key: tabName },
          },
        ],
      } = useColumns();
      this.visible = false;
      this.tabName = tabName;
      this.params = this.$init.params([...TabColumns, ...TableColumns]);
    },
    //增行
    async useRowAdd(prop) {
      const { TabColumns } = this;
      const { TableColumns } = TabColumns.find(
        ({ item: { key } }) => key === prop
      );
      this.params[prop].push({
        delFlag: "0",
        $index: new Date().getTime(),
        ...this.$init.params(TableColumns),
      });
    },
    //删行
    async useRowRemove(prop, scope) {
      // const { addType } = this.$props;
      if (scope.row.id) {
        this.params[prop].forEach(e => {
          if(e.id == scope.row.id){
            e.delFlag = '2'
          }
        });
      }else{
        this.params[prop] = this.params[prop].filter(item => item.$index != scope.row.$index);
      }
      console.log("this.params[prop]",this.params[prop]);
    },
    //确认
    async useSubmit(prop) {
      this.$refs[prop].$refs[prop].validate(async (valid) => {
        if (valid) {
          try {
            this.loading = true;
            const { addType } = this.$props;
            let res = null;
            if (addType === "add") {
              res = await addTargetTemplate(this.params);
            }
            if (addType === "edit") {
              res = await updateTargetTemplate(this.params);
            }
            if (res.code === 200) {
              this.hide();
              this.$emit("success");
              this.$notify.success(res.msg);
            }
          } catch (err) {
            // catch
            console.error(err);
          } finally {
            // finally
            this.loading = false;
          }
        } else {
          return false;
        }
      });
    },
    //保存并新增
    useSaveAndAdd(prop){
      this.$refs[prop].$refs[prop].validate(async (valid) => {
        if (valid) {
          try {
            this.loading = true;
            const { addType } = this.$props;
            let res = null;
            if (addType === "add") {
              res = await addTargetTemplate(this.params);
            }
            if (addType === "edit") {
              res = await updateTargetTemplate(this.params);
            }
            if (res.code === 200) {
              this.$notify.success(res.msg);
              this.params={};
            }
          } catch (err) {
            // catch
            console.error(err);
          } finally {
            // finally
            this.loading = false;
          }
        } else {
          return false;
        }
      });
    },
    //重置周期
    useResetCycle(){
      if(!this.params.startTime || !this.params.deadlineTime || !this.params.cycle){
        this.$modal.msgError("开始日期、结束日期、周期不能存在空值！");
        return;
      }
      if(this.params.startTime > this.params.deadlineTime){
        this.$modal.msgError("开始日期不能大于结束日期！");
        return;
      }
      this.params.cycles = [];
      var cycles = [];
      var start = new Date(this.params.startTime);
      var deadline = new Date(this.params.deadlineTime);
      start.setHours( 0, 0, 0);
      deadline.setHours( 0, 0, 0);
      if(this.params.cycle == 'period'){
        cycles.push({
          name:'目标期间',
          startTime:start,
          deadlineTime:deadline,
        });
      }else{
        while(deadline >= start){
          console.log(start);
          if(this.params.cycle == 'day'){
            var cy = {
              name:this.formatDateTime(start, 'yyyy-MM-dd'),
              startTime:start,
              deadlineTime:start,
            }
            console.log(cy);
            cycles.push(cy);
            start = start.setDate(start.getDate()+1);
            start = new Date(start);
          }
          if(this.params.cycle == 'week'){
            var de = start;
            var cy = {
              name:this.formatDateTime(start, 'yyyy-MM-dd'),
              startTime:start,
              deadlineTime:de.setDate(de.getDate()+7),
            }
            console.log(cy);
            cycles.push(cy);
            start = start.setDate(start.getDate()+7);
            start = new Date(start);
          }
          if(this.params.cycle == 'month'){
            var de = start;
            var cy = {
              name:this.formatDateTime(start, 'yyyy-MM-dd'),
              startTime:start,
              deadlineTime:de.setDate(de.getDate()+30),
            }
            console.log(cy);
            cycles.push(cy);
            start = start.setDate(start.getDate()+30);
            start = new Date(start);
          }
          if(this.params.cycle == 'season'){
            var de = start;
            var cy = {
              name:this.formatDateTime(start, 'yyyy-MM-dd'),
              startTime:start,
              deadlineTime:de.setDate(de.getDate()+90),
            }
            console.log(cy);
            cycles.push(cy);
            start = start.setDate(start.getDate()+90);
            start = new Date(start);
          }
        }
      }
      this.params.cycles = cycles;
      console.log('this.params.cycles',this.params.cycles);
    },
    //日期名称格式化
    formatDateTime(date, format) {
      const o = {
        'M+': date.getMonth() + 1, // 月份
        'd+': date.getDate(), // 日
        'h+': date.getHours() % 12 === 0 ? 12 : date.getHours() % 12, // 小时
        'H+': date.getHours(), // 小时
        'm+': date.getMinutes(), // 分
        's+': date.getSeconds(), // 秒
        'q+': Math.floor((date.getMonth() + 3) / 3), // 季度
        S: date.getMilliseconds(), // 毫秒
        a: date.getHours() < 12 ? '上午' : '下午', // 上午/下午
        A: date.getHours() < 12 ? 'AM' : 'PM', // AM/PM
      };
      if (/(y+)/.test(format)) {
        format = format.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length));
      }
      for (let k in o) {
        if (new RegExp('(' + k + ')').test(format)) {
          format = format.replace(
            RegExp.$1,
            RegExp.$1.length === 1 ? o[k] : ('00' + o[k]).substr(('' + o[k]).length)
          );
        }
      }
      return format;
    }
  },
  created() {
  },
  mounted() {},
  destroyed() {},
};
</script>
<template>
  <el-button v-bind="$attrs" v-on="$listeners" @click="open">
    {{ title }}
    <el-drawer
      :size="width"
      :title="title"
      :visible.sync="visible"
      append-to-body
      destroy-on-close
      @close="hide"
    >
      <el-super-form
        v-model="params"
        :dict="dict"
        :rules="rules"
        :size="$attrs.size"
        :columns="TableColumns"
        ref="superForm"
        label-width="auto"
        label-position="right"
        style="padding: 20px"
      >
        <!-- <template slot="puOrgName" slot-scope="scope">
          <component
            v-bind="scope.attr"
            v-model="scope.row[scope.item.key]"
            :size="$attrs.size"
            :source.sync="scope.row"
            @change="changePuOrgName({ ...scope, select: $event })"
          >
          </component
        ></template> -->
      </el-super-form>
      <el-tabs v-model="tabName" style="padding: 0 20px 20px">
        <el-tab-pane
          v-for="({ item, TableColumns: columns }, index) in TabColumns"
          :key="index"
          :label="item.title"
          :name="item.key"
          lazy
        >
          <el-super-table
            v-model="params[item.key]"
            :dict="dict"
            :ref="tabName"
            :columns="columns"
            :size="$attrs.size"
          >
            <!-- <template slot="materialName" slot-scope="scope">
              <component
                v-bind="scope.attr"
                v-model="scope.row[scope.item.key]"
                :size="$attrs.size"
                :source.sync="scope.row"
                @change="changeMaterialName(scope)"
              >
              </component>
            </template> -->
            <el-table-column fixed="right" label="操作" width="100">
              <template slot="header" slot-scope="scope">
                <el-button v-if="tabName == 'cycles'" type="primary" size="mini" @click="useResetCycle">重算周期</el-button>
                <el-button
                  v-else
                  circle
                  icon="el-icon-plus"
                  :size="$attrs.size"
                  @click="useRowAdd(tabName)"
                >
                </el-button>
              </template>
              <template slot-scope="scope">
                <el-button
                  v-if="tabName == 'indexs' || tabName == 'dimensionalitys'"
                  circle
                  icon="el-icon-minus"
                  :size="$attrs.size"
                  @click.native.prevent="useRowRemove(tabName, scope)"
                >
                </el-button>
              </template>
            </el-table-column>
          </el-super-table>
        </el-tab-pane>
      </el-tabs>
      <div style="padding: 20px; text-align: right">
        <el-button :size="$attrs.size" :loading="loading" @click="hide"
          >取 消</el-button
        >
        <!-- <el-button
          type="primary"
          :size="$attrs.size"
          :loading="loading"
          @click="useSaveAndAdd('superForm')"
          >保存并新增</el-button
        > -->
        <el-button
          type="primary"
          :size="$attrs.size"
          :loading="loading"
          @click="useSubmit('superForm')"
          >确 认</el-button
        >
      </div>
    </el-drawer>
  </el-button>
</template>

<style scoped>
::v-deep .el-table__row.is-hidden {
  display: none;
}
</style>
