<template>
  <div>
    <div class="edit-container">
      <div class="edit-top">
        <div class="left-top">
          <img src="@/assets/images/back.png" @click="cancel()" />
          <div class="left-title"></div>
        </div>
        <div class="center-top">
          <div>
            <div :class="showIndex == 1 ? 'el-step__icon is-text is-finish' : 'el-step__icon is-text is-info'">
              <div class="el-step__icon-inner">1</div>
            </div>
            {{ $t('page.business.study.studyFormFill.jcsz') }}
          </div>
          <div class="line"></div>
          <div>
            <div :class="showIndex == 2 ? 'el-step__icon is-text is-finish' : 'el-step__icon is-text is-info'">
              <div class="el-step__icon-inner">2</div>
            </div>
            {{ $t('page.business.study.studyFormFill.bdtb') }}
          </div>
        </div>
        <div class="right-top">
          <el-button @click="cancel()">{{ $t('form.cancel') }}</el-button>
          <template v-if="showIndex == 1">
            <el-button @click="save">{{ $t('page.business.study.studyFormFill.zc') }}</el-button>
            <el-button type="primary" @click="next">{{ $t('page.business.study.studyFormFill.next') }}</el-button>
          </template>
          <template v-else>
            <el-button @click="saveNext">{{ $t('page.business.study.studyFormFill.save') }}</el-button>
            <el-button type="primary" @click="showApprove">{{ $t('page.business.study.studyFormFill.submit')
            }}</el-button>
            <el-button type="primary" @click="pre">{{ $t('page.business.study.studyFormFill.pre') }}</el-button>
          </template>
        </div>
      </div>
      <div class="edit-content">
        <div class="content" style="width:60%" v-show="showIndex == 1">
          <el-form ref="form" :model="form" :rules="rules" label-width="120px">
            <el-row>
              <el-col :span="24">
                <el-form-item :label="bdmbTitle" prop="templateId">
                  <SelectTemplate v-model="form.templateId" :disabled="form.id && form.id !== ''"
                    :name="form.templateMc" @change="selectTemplateChange" :needPre="1" />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="24">
                <el-form-item :label="$t('page.business.form.bdmc')" prop="bdmc">
                  <el-input type="text" v-model="form.bdmc" maxlength="50" :placeholder="$t('form.placeholderInput')" />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="24">
                <el-form-item :label="$t('page.business.study.studyFormFill.sfbl')" prop="sfbl">
                  <el-select v-model="form.sfbl" :placeholder="$t('form.placeholderSelect')"
                    :disabled="form.id && form.id !== ''">
                    <el-option :label="$t('page.business.study.studyFormFill.yes')" value="是" />
                    <el-option :label="$t('page.business.study.studyFormFill.no')" value="否" />
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="24">
                <el-form-item :label="$t('page.business.study.studyFormFill.bdsm')" prop="bdsm">
                  <el-input type="textarea" v-model="form.bdsm" :rows="5" maxlength="500"
                    :placeholder="$t('form.placeholderInput')">
                  </el-input>
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </div>
        <div class="content" v-if="showIndex == 2">
          <TemplateTable emitName="onFillCallback" @onFillCallback="onFillCallback" ref="templateTable"
            :sn="form.templateSn" :templateData="templateData" fillType="actFill" />
        </div>
      </div>
    </div>

    <el-dialog :title="$t('page.business.study.studyFormFill.tjjl')" :visible.sync="openApprove" width="1200px"
      append-to-body :close-on-click-modal="false">
      <el-form ref="formApprove" :model="formApprove" :rules="rulesApprove" label-width="120px">
        <div class="sbzdtcma"> <input type="text"> <input type="password"> </div>
        <el-row v-if="form.sftb == 1">
          <el-col :psna="24">
            <el-form-item>
              <div><el-checkbox v-model="formApprove.sfcz" @change="sfczChange">{{
                $t('page.business.study.studyFormFill.cz') }}</el-checkbox>
                <el-button type="primary" v-if="formApprove.sfcz" @click="addCz" style="margin-left: 10px;">{{
                  $t('page.business.study.studyFormFill.tjcz') }}</el-button>
              </div>
              <template v-if="formApprove.sfcz">
                <div v-if="czlist.length > 0">
                  <el-card class="box-card" v-for="(citem, cindex) in czlist" :key="'cz' + cindex"
                    style="margin-top: 10px;">
                    <div slot="header" class="clearfix">
                      <div style="display: flex;justify-content: space-between;">
                        <div style="display: flex;">
                          <div> 处置方式：</div>
                          <div>
                            <BusinessSelect v-model="citem.czfs" dictType="business_czfs" style="width: 200px;">
                            </BusinessSelect>
                          </div>
                        </div>
                        <div>
                          <el-button type="danger" icon="el-icon-delete" circle @click="delcz(cindex)"></el-button>
                        </div>
                      </div>
                    </div>
                    <el-checkbox-group v-model="citem.list">
                      <el-checkbox :label="item.bh" v-for="item in resource" :key="'icz' + item.bh"
                        :disabled="getDisabledCz(item.bh, cindex)"></el-checkbox>
                    </el-checkbox-group>
                  </el-card>
                </div>
              </template>
            </el-form-item>
          </el-col>
          <el-col :psna="24">
            <el-form-item>
              <div><el-checkbox v-model="formApprove.sfcc" @change="sfccChange">{{
                $t('page.business.study.studyFormFill.cc') }}</el-checkbox>
                <el-button type="primary" v-if="formApprove.sfcc" @click="addCc" style="margin-left: 10px;">{{
                  $t('page.business.study.studyFormFill.tjcc') }}</el-button>
              </div>
              <template v-if="formApprove.sfcc">
                <div v-if="cclist.length > 0">
                  <el-card class="box-card" v-for="(citem, cindex) in cclist" :key="'cz' + cindex"
                    style="margin-top: 10px;">
                    <div slot="header" class="clearfix">
                      <div style="display: flex;justify-content: space-between;">
                        <div style="display: flex;">
                          <div style="display: flex;">
                            <div> 存储条件：</div>
                            <div>
                              <BusinessSelect v-model="citem.cctj" dictType="business_cctj" style="width: 200px;">
                              </BusinessSelect>
                            </div>
                          </div>
                          <div style="display: flex; margin-left: 10px;">
                            <div> 存储位置：</div>
                            <div>
                              <BusinessSelect v-model="citem.ccwz" dictType="business_ccwz" style="width: 200px;">
                              </BusinessSelect>
                            </div>
                          </div>
                        </div>
                        <div>
                          <el-button type="danger" icon="el-icon-delete" circle @click="delcc(cindex)"></el-button>
                        </div>
                      </div>
                    </div>
                    <el-checkbox-group v-model="citem.list">
                      <el-checkbox :label="item.bh" v-for="item in resource" :key="'icz' + item.bh"
                        :disabled="getDisabledCc(item.bh, cindex)"></el-checkbox>
                    </el-checkbox-group>
                  </el-card>
                </div>
              </template>
            </el-form-item>
          </el-col>
          <el-col :psna="24">
            <el-form-item>
              <div>{{ $t('page.business.study.studyFormFill.yltj') }}</div>
              <div v-for="(item, index) in resource" :key="'r' + index">
                {{ item.bh }}
                <el-input type="text" v-model="item.syl" maxlength="50" style="width: 250px;">
                  <template slot="append">
                    <div style="width: 70px;">
                      <BusinessSelect v-model="item.syldw" dictType="business_tjdw">
                      </BusinessSelect>
                    </div>
                  </template>
                </el-input>
              </div>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item :label="$t('form.qmyy')" prop="qmyy">
              <el-input type="text" :value="formApprove.qmyy" maxlength="50" disabled
                :placeholder="$t('form.placeholderInput')" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item :label="$t('form.remark')" prop="remark">
              <el-input type="textarea" v-model="formApprove.remark" :rows="5" maxlength="500"
                :placeholder="$t('form.placeholderInput')">
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item :label="$t('form.signer')">
              <el-input type="text" v-model="nickName" maxlength="50" disabled
                :placeholder="$t('form.placeholderInput')" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item :label="$t('form.password')" prop="qmrmm">
              <el-input type="password" v-model="formApprove.qmrmm" maxlength="20"
                :placeholder="$t('form.placeholderInput')" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="tj">{{ $t('form.confirm') }}</el-button>
        <el-button @click="openApprove = false">{{ $t('form.cancel') }}</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { studyFormFill_bc, studyFormFill_updateBdnr, studyFormFill_tj, studyFormFill_info } from "@/api/business/study/studyFormFill"
import { study_info } from "@/api/business/study/study"
import { mapGetters } from 'vuex'
import SelectTemplate from "@/views/business/comps/select/SelectTemplate";
import SelectDeptUser from '@/views/business/comps/select/SelectDeptUser';
import TemplateTable from '@/views/business/comps/template/TemplateTable';
import BusinessSelect from '@/views/business/comps/select/BusinessSelect';
import { deepClone } from "@/utils/index";

export default {
  name: "Bj",
  components: { SelectTemplate, SelectDeptUser, TemplateTable, BusinessSelect },
  data() {
    return {
      open: false,
      showIndex: 1,
      form: {},
      rules: {
        bdmc: [{
          required: true,
          message: ' ',
          trigger: 'blur'
        }],
        templateId: [{
          required: true,
          message: ' ',
          trigger: 'blur'
        }],
        sfbl: [{
          required: true,
          message: ' ',
          trigger: 'blur'
        }],

      },
      czlist: [],
      cclist: [],
      openApprove: false,
      formApprove: {
        id: null,
        qmyy: this.$t('page.business.study.studyFormFill.txbtjjl'),
        remark: '',
        bdnr: '',
        resource: '',
        qmrmm: '',
        sfcz: false,
        czfs: '',
        czfsqt: '',
        czids: '',
        sfcc: false,
        cctj: '',
        ccwz: '',
        ccids: '',
      },
      resource: [],
      bdmbTitle: this.$t('page.business.form.bdmb'),
      rulesApprove: {
        qmrmm: [{
          required: true,
          message: ' ',
          trigger: 'blur'
        }]
      },
      templateData: {}
    }
  },
  computed: {
    ...mapGetters([
      'nickName', 'name'
    ]),
  },
  created() {
    this.getInfo()
  },
  methods: {
    onFillCallback(data) {
      console.log("data:" + JSON.stringify(data))
      console.log("formdata:" + JSON.stringify(this.$refs.templateTable.getFilledFormData()))
      // {"type":"fieldChanged","newRecord":{"userNameCn":"谭飞","userNameEn":"tf","key":"_versionNum","field":"试验基本信息-版本号","oldValue":"1.0","value":"1.0333","title":"修改记录","time":"2026-01-14 19:44:02"},"resourceList":[{"userNameCn":"谭飞","userNameEn":"tf","key":"_versionNum","field":"试验基本信息-版本号","oldValue":"1.0","value":"1.0","title":"修改记录","time":"2026-01-14 19:43:57"}]}
      if (data.type == 'fieldChanged') {
        studyFormFill_updateBdnr(
          {
            id: this.form.id,
            bdnr: JSON.stringify(this.$refs.templateTable.getFilledFormData()),
            zdxgjl: JSON.stringify(data.resourceList),
            filedValue: JSON.stringify(data.newRecord)
          }
        ).then(response => {
        })
      }
    },
    delcc(index) {
      this.cclist.splice(index, 1)
    },
    delcz(index) {
      this.czlist.splice(index, 1)
    },
    addCz() {
      this.czlist.push({
        list: [],
        czfs: ''
      })
    },
    addCc() {
      this.cclist.push({
        list: [],
        cctj: '',
        ccwz: ''
      })
    },
    getInfo() {
      let formId = this.$route.params.formId
      let studyId = this.$route.params.studyId
      let fromYt = this.$route.params.fromYt
      this.reset()
      if (parseInt(formId) > 0) {
        if (fromYt + '' == "10") {
          this.showIndex = 1
          this.bdmbTitle = this.$t('page.business.study.studyFormFill.ytbd')
        } else {
          this.showIndex = 2
        }
        this.$modal.loading()
        studyFormFill_info({ id: formId }).then(response => {
          this.form = response.data
          this.form.qmyy = this.$t('page.business.study.studyFormFill.zztjyzbd')
          this.templateData = deepClone(this.form)
          this.$modal.closeLoading()
        })
      } else {
        this.showIndex = 1
        this.$modal.loading()
        study_info({ id: studyId }).then(response => {
          this.form = _.merge({}, this.form, { stydyId: studyId, resourceStudy: response.data.resource, sftb: 1 })
          this.templateData = deepClone(this.form)
          this.$modal.closeLoading()
        })
      }
    },
    getDisabledCz(bh, idx) {
      let mark = false
      for (var i = 0; i < this.czlist.length; i++) {
        if (idx != i) {
          for (var j = 0; j < this.czlist[i].list.length; j++) {
            if (this.czlist[i].list[j] == bh) {
              mark = true;
              break
            }
          }
        }
      }
      return mark
    },
    getDisabledCc(bh, idx) {
      let mark = false
      for (var i = 0; i < this.cclist.length; i++) {
        if (idx != i) {
          for (var j = 0; j < this.cclist[i].list.length; j++) {
            if (this.cclist[i].list[j] == bh) {
              mark = true;
              break
            }
          }
        }
      }
      return mark
    },
    sfczChange() {
      if (!this.formApprove.sfcz) {
        this.czlist = []
      }
    },
    sfccChange() {
      if (!this.formApprove.sfcc) {
        this.cclist = []
      }
    },
    async showApprove() {
      let that = this
      let content = await that.$refs.templateTable.getFormData()
      if (content) {
        that.resetApprove()
        that.formApprove.id = that.form.id
        that.formApprove.bdnr = JSON.stringify(content)
        that.resource = that.$refs.templateTable.getResource()
        that.openApprove = true
      }
    },
    resetApprove() {
      this.formApprove = {
        id: null,
        qmyy: this.$t('page.business.study.studyFormFill.txbtjjl'),
        remark: '',
        bdnr: '',
        resource: '',
        qmrmm: '',
        sfcz: false,
        czlist: '',
        sfcc: false,
        cclist: '',
      }
      this.resetForm("formApprove")
    },
    pre() {
      this.showIndex = 1
    },
    next() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.showIndex = 2
          this.$modal.loading()
          studyFormFill_bc(this.form).then(response => {
            this.form = response.data
            this.showIndex = 2
          }).finally(() => {
            this.$modal.closeLoading()
          })
        }
      })
    },
    selectTemplateChange(val) {
      this.form.bdnr = val.content
      this.form.templateMc = val.name
      this.form.bdmc = val.name
      this.form.templateSn = val.sn
    },
    cancel() {
      let data = localStorage.getItem(this.$route.params.key)
      if (data && data != '') {
        let params = JSON.parse(data)
        const obj = { path: params.url }
        this.$tab.closeOpenPage(obj)
      }
    },
    reset() {
      this.form = {
        id: null,
        studyId: null,
        bdbh: null,
        bdmc: null,
        bdsm: null,
        templateId: null,
        templateMc: null,
        templateSn: null,
        bdnr: null,
        resource: null,
        resourceStudy: null,
        fzrsh: null,
        shryId: null,
        sfbl: null,
        shryMc: null,
      }
      this.resetForm("form")
    },
    selectDeptUserChange(val) {
      this.form.shryMc = val.name
    },
    save() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.$modal.loading()
          studyFormFill_bc(this.form).then(response => {
            this.$modal.closeLoading()
            this.cancel()
          }).finally(() => {
            this.$modal.closeLoading()
          })
        }
      })
    },
    async saveNext() {
      let content = await this.$refs.templateTable.getFormData()
      if (content) {
        this.form.bdnr = JSON.stringify(content)
        this.$modal.loading()
        studyFormFill_bc(this.form).then(response => {
          this.$modal.closeLoading()
          this.cancel()
        }).finally(() => {
          this.$modal.closeLoading()
        })
      }
    },
    tj() {
      let that = this
      this.$refs["formApprove"].validate(valid => {
        if (valid) {
          that.$modal.loading()
          that.formApprove.resource = JSON.stringify(that.resource)
          if (that.czlist.length > 0) {
            that.formApprove.czlist = JSON.stringify(that.czlist)
          }
          if (that.cclist.length > 0) {
            that.formApprove.cclist = JSON.stringify(that.cclist)
          }
          studyFormFill_tj(that.formApprove).then(response => {
            that.openApprove = false
            that.$modal.closeLoading()
            that.cancel()
          }).finally(() => {
            that.$modal.closeLoading()
          })
        }
      })
    }
  }
}
</script>
