<template>
  <div>
    <el-card>
      <el-form :model="form" :rules="rules" ref="form" label-width="auto" :disabled="this.pageStu == 'see'">
        <el-row :gutter="10">
          <el-col :span="1.5">
            <el-form-item label="单据编号" prop="code">
              <el-input
                v-model="form.code"
                size="mini"
                disabled
                style="width: 200px"
              />
              <!-- <div>{{form.code}}</div> -->
            </el-form-item>
          </el-col>
          <el-col :span="1.5">
            <el-form-item label="单据日期" prop="date">
              <el-date-picker
                  v-model="form.date"
                  clearable
                  type="date"
                  value-format="yyyy-MM-dd"
                  size="mini"
                  style="width: 200px"
                >
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="1.5">
            <el-form-item label="目标名称" prop="name">
              <el-input
                v-model="form.name"
                size="mini"
                style="width: 200px"
              />
            </el-form-item>
          </el-col>
          <!-- <el-col :span="1.5">
            <el-form-item label="包含下级组织" >
              <el-select v-model="form.includeOrg" size="mini" style="width: 200px">
                <el-option
                  v-for="dict in dict.type.sys_yes_no"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col> -->
          <el-col :span="1.5">
            <el-form-item label="模板" prop="template">
              <dr-popover-select size="mini" v-model="form.templateName" title="模板" type="MK_TARGET_TEMPLATE_PARAM" :dataMapping="{
                  template: 'id',
                  templateName: 'name',
                }" :source.sync="form"
              >
              </dr-popover-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-card shadow="never">
          <el-descriptions title="模板信息">
            <el-descriptions-item label="年度">{{template.year}}</el-descriptions-item>
            <el-descriptions-item label="开始日期">{{template.startTime}}</el-descriptions-item>
            <el-descriptions-item label="结束日期">{{template.deadlineTime}}</el-descriptions-item>
            <el-descriptions-item label="周期">
              <div v-for="dict in dict.type.mk_periodic_unit" v-if="template.cycle == dict.value">
                  <el-tag size="small">{{dict.label}}</el-tag>
                </div>
            </el-descriptions-item>
            <el-descriptions-item label="维度">
              <div v-for="d in template.dimensionalitys">
                <!-- <el-tag size="small">{{d.dimensionality}}</el-tag> -->
                <div v-for="dict in dict.type.mk_dimensionality" v-if="d.dimensionality == dict.value">
                  <el-tag size="small">{{dict.label}}</el-tag>
                </div>
              </div>
            </el-descriptions-item>
            <el-descriptions-item label="指标">
              <div v-for="d in template.indexs">
                <!-- <el-tag size="small">{{d.target}}</el-tag> -->
                <div v-for="dict in dict.type.mk_index_type" v-if="d.target == dict.value">
                  <el-tag size="small">{{dict.label}}</el-tag>
                </div>
              </div>
            </el-descriptions-item>
            <el-descriptions-item label="展开方式">
              <div v-for="dict in dict.type.mk_expansion_mode" v-if="template.unfold == dict.value">
                  <el-tag size="small">{{dict.label}}</el-tag>
                </div>
            </el-descriptions-item>
          </el-descriptions>
        </el-card>
      </el-form>
    </el-card>
    <el-card  style="height:500px">
      <Item ref="child" v-if="isItem" :pageStu="pageStu" :template="template" :form="form" :columns="headers" :latestTemplate="latestTemplate"></Item>
    </el-card>
    <el-card>
      <div class="btn_group">
        <el-col :span="1.5">
          <el-button size="mini" plain @click="useBack">取消</el-button>
        </el-col>
        <el-col :span="1.5" style="margin: 0 10px;">
          <el-button type="primary" size="mini" plain @click="useSave" v-if="pageStu == 'add' || pageStu == 'edit'">保存</el-button>
        </el-col>
      </div>
    </el-card>
  </div>
</template>

<script>
import Item from './item.vue'
import { getTargetTemplate,getHeaderData } from "@/api/business/spd/starget/targetTemplate";
import { getTarget,addTarget,updateTarget } from "@/api/business/spd/starget/target";
export default {
  name: 'add',
  dicts: ['sys_yes_no','mk_periodic_unit','mk_dimensionality','mk_index_type','mk_expansion_mode'],
  props: ['pageStu','row', 'disable'],
  components: {Item},
  model: {
    prop: 'isList',
    event: 'jugislist'
  },
  data() {
    return {
      template:{},
      form:{},
      //表单校验
      rules: {
        date: [
          { required: true, message: "单据日期不能为空", trigger: "blur" },
        ],
        name: [
          { required: true, message: "目标名称不能为空", trigger: "blur" },
        ],
        template: [
          { required: true, message: "模板不能为空", trigger: "blur" },
        ],
      },
      //子表表头数据
      headers:[],
      //遮罩
      loading: false,
      //是否展示Item组件
      isItem:false,
      //是否为最新模板
      latestTemplate:false,
    }
  },
  async created() {
    if(this.pageStu == 'add'){
      this.form.date = new Date();
    }
    if(this.pageStu == 'edit' || this.pageStu == 'see') {
      await this.fetchTarget(this.row);
      await this.fetchTemplate(this.row.template);
      await this.fetchHeaderData(this.row.template);
      this.latestTemplate = true;
      this.isItem = true;
    }
  },
  watch: {
	  'form.template': {
      async handler(newVal) {
        console.log('111');
        this.isItem = false;
        await this.fetchTemplate(newVal);
        await this.fetchHeaderData(newVal);
        this.isItem = true;
      },
      immediate:false,
    }
  },
  methods: {
    //保存
    async useSave(){
      let passrule = false;
      this.$refs["form"].validate((valid) => {
        if (valid) {
            passrule = true;
          }
      });
      if(passrule){
        try {
          this.form.items = this.$refs.child.merge();
          if(!this.form.items.length){
            this.$modal.msgError("子表数据不能为空！");
            return;
          }
          console.log('this.form',this.form);
          this.loading = true;
          let res = null;
          if(this.pageStu == 'add'){
            res = await addTarget(this.form);
          }
          if(this.pageStu == 'edit'){
            res = await updateTarget(this.form);
          }
          if (res.code === 200) {
            this.$modal.msgSuccess("保存成功");
            this.useBack();
          }
        } catch (err) {
          // catch
          console.error(err);
        } finally {
          this.loading = false;
        }
      }
    },
    //返回
    useBack(){
      this.$emit('jugislist', true)
      this.$emit('refresh')
    },
    //查询目标模板
    async fetchTemplate(id) {
      try {
        this.loading = true;
        const { code, data } = await getTargetTemplate(id);
        if (code === 200) {
          this.template = data;
          return true;
        } else {
          return false;
        }
      } catch (err) {
        // catch
        console.error(err);
      } finally {
        // finally
        this.loading = false;
      }
    },
    //查询详情
    async fetchTarget(row){
      await getTarget(row.id).then(res => {
        if (res.code === 200) {
          this.form = res.data
         }
      })
    },
    //查询动态表头数据
    async fetchHeaderData(id){
      await getHeaderData(id).then(res => {
        if (res.code === 200) {
          this.headers = res.rows
        }
      })
    },
  }
}
</script>

<style lang="scss" scoped>
.btn_group {
  width: 100%;
  margin: 20px 0;
  display: flex;
  justify-content: right;
} 
</style>