<template>
  <audit-form-top-banner :handel-save-form="saveForm" :form-data="mode" @handelSaveForm="saveForm">
    <sd-detail-form
      ref="myForm"
      form-id="iamWorkFlow"
      page-id="audit/node/workflow/iamWorkFlow"
      :record-id="this.$route.query.record ? parseInt(this.$route.query.record) : null"
      :class="$style.form"
      :read-only="readOnly"
      @close="close(true)"
      @saved="saved"
      @sdFormReady="sdFormReady"
    >
      <template v-slot="{ model, fields }">
        <table
          ><tr
            ><td style="padding-left:5px;border:none">
              <audit-advanced-group
                :expand="workExpand"
                :expand-str="'workExpand'"
                :group-label="'基本信息'"
                tablestyle="''"
                @changedClick="changedClick"
              ></audit-advanced-group> </td></tr
        ></table>

        <table v-show="workExpand">
          <tr>
            <!-- 流程名称 -->
            <sd-form-item-td name="lcName">
              <a-form-model-item
                :rules="[
                  {
                    validator: validator,
                    trigger: ['change', 'blur'],
                  },
                ]"
                prop="lcName"
              >
                <a-input v-model="model.lcName"></a-input>
              </a-form-model-item>
            </sd-form-item-td>
            <!-- 是否默认 -->
            <sd-form-item-td
              v-if="(mode === 'VIEW') | (isfalse === true)"
              :input-props="{ disabled: isfalse }"
              name="isDefault"
            />
            <sd-form-item-td v-else name="isDefault">
              <template v-slot:read-and-edit="{ editable }">
                <a-radio-group v-model="model.isDefault" @change="ischange(model)">
                  <a-radio
                    v-for="(v, index) in fields.isDefault.attr.selectListItem"
                    :key="index"
                    :allow-clear="true"
                    :value="v.value"
                    >{{ v.label }}</a-radio
                  >
                </a-radio-group>
              </template>
            </sd-form-item-td>
          </tr>
          <tr v-show="model.isDefault === '0'" v-if="mode === 'VIEW'">
            <sd-form-item-td name="orgScopeMember" :colspan="3" />
          </tr>
          <tr v-else>
            <td v-show="model.isDefault === '0'" class="ant-form-item-label">
              <label>适用机构范围</label>
            </td>
            <td v-show="model.isDefault === '0'" :colspan="3">
              <AuditGroupPicker
                v-model="model.orgScopeMember"
                :single="false"
                :read-only="false"
                :root-node="rootNode"
                :selectall="rootNode === undefined ? true : false"
                :top-node-text="rootNode === undefined ? '审计机构库' : ''"
                :treeparams="
                  rootNode === undefined
                    ? {
                        formId: 'IAM_ORG',
                        idColumnId: 'id',
                        nameColumnId: 'org_name',
                        parentColumnId: 'parent_id',
                        otherColumnId: ['org_id', 'creation_time'],
                        configId: '11',
                        moduleId: 'iamWorkFlow',
                      }
                    : { moduleId: 'iamWorkFlow' }
                "
              />
            </td>
          </tr>
          <tr>
            <!-- 说明 -->
            <sd-form-item-td name="remarks" :colspan="3">
              <a-textarea v-model="model.remarks" />
            </sd-form-item-td>
          </tr>
          <tr>
            <!-- 编制人员 -->
            <sd-form-item-td name="creatorName" />
            <!-- 编制日期 -->
            <sd-form-item-td v-if="initparams(model)" name="creationTime" />
          </tr>
        </table>
      </template>
    </sd-detail-form>

    <div :class="$style.item2">
      <div :class="$style.head"><a-icon type="double-right" />准备阶段</div>
      <div :class="$style.body">
        <div v-for="(v, i) in zbDate" :key="i"
          ><div><a-icon type="right" />{{ v.nodeName }}</div
          ><div>
            <a-button
              icon="check-circle"
              :style="v.nodeStatus === 'PROJECT_BX' ? 'color: red;' : ''"
              @click="onclickchange('PROJECT_BX', v)"
              >必选</a-button
            >
            <a-button
              icon="check-circle"
              :style="v.nodeStatus === 'PROJECT_MR' ? 'color: red;' : ''"
              @click="onclickchange('PROJECT_MR', v)"
              >默认</a-button
            >
            <a-button
              icon="check-circle"
              :style="v.nodeStatus === 'PROJECT_JY' ? 'color: red;' : ''"
              @click="onclickchange('PROJECT_JY', v)"
              >禁用</a-button
            >
          </div></div
        >
      </div>
    </div>

    <div :class="$style.item2">
      <div :class="$style.head"><a-icon type="double-right" />实施阶段</div>
      <div :class="$style.body">
        <div v-for="(v, i) in ssDate" :key="i"
          ><div><a-icon type="right" />{{ v.nodeName }}</div
          ><div>
            <a-button
              icon="check-circle"
              :style="v.nodeStatus === 'PROJECT_BX' ? 'color: red;' : ''"
              @click="onclickchange('PROJECT_BX', v)"
              >必选</a-button
            >
            <a-button
              icon="check-circle"
              :style="v.nodeStatus === 'PROJECT_MR' ? 'color: red;' : ''"
              @click="onclickchange('PROJECT_MR', v)"
              >默认</a-button
            >
            <a-button
              icon="check-circle"
              :style="v.nodeStatus === 'PROJECT_JY' ? 'color: red;' : ''"
              @click="onclickchange('PROJECT_JY', v)"
              >禁用</a-button
            >
          </div></div
        >
      </div>
    </div>

    <div :class="$style.item2">
      <div :class="$style.head"><a-icon type="double-right" />报告阶段</div>
      <div :class="$style.body">
        <div v-for="(v, i) in bgDate" :key="i"
          ><div><a-icon type="right" />{{ v.nodeName }}</div
          ><div>
            <a-button
              icon="check-circle"
              :style="v.nodeStatus === 'PROJECT_BX' ? 'color: red;' : ''"
              @click="onclickchange('PROJECT_BX', v)"
              >必选</a-button
            >
            <a-button
              icon="check-circle"
              :style="v.nodeStatus === 'PROJECT_MR' ? 'color: red;' : ''"
              @click="onclickchange('PROJECT_MR', v)"
              >默认</a-button
            >
            <a-button
              icon="check-circle"
              :style="v.nodeStatus === 'PROJECT_JY' ? 'color: red;' : ''"
              @click="onclickchange('PROJECT_JY', v)"
              >禁用</a-button
            >
          </div></div
        >
      </div>
    </div>
  </audit-form-top-banner>
</template>

<script>
import { Modal } from 'ant-design-vue'
import debounce from 'lodash.debounce'
import axios from '@/common/services/axios-instance'
import { getUserInfo } from '@/common/store-mixin'
import crossWindowWatcher from '@/common/services/cross-window-watcher'
import auditFormTopBanner from '../../../components/audit-form-top-banner'
import auditAdvancedGroup from '../../../components/audit-advanced-group.vue'
import auditAdvancedGroupMixins from '../../../components/audit-advanced-group-mixins'
import AuditGroupPicker from '../../../components/picker/audit-group-picker.vue'
import AuditWorkflowService from './audit-workflow-service'
import components from './_import-components/audit-workflow-form-import'

export default {
  name: 'AuditWorkflowForm',
  metaInfo: {
    title: '作业流程',
  },
  components: {
    ...components,
    auditAdvancedGroup,
    AuditGroupPicker,
    auditFormTopBanner,
  },
  mixins: [auditAdvancedGroupMixins],
  data() {
    return {
      mode: null,
      id: '',
      isfalse: false,
      readOnly: false,
      saveFlag: true,
      workExpand: true,
      zbDate: [],
      ssDate: [],
      bgDate: [],
      rootNode: {},
    }
  },
  created() {
    let userInfo = getUserInfo()
    getUserInfo().roles.find((item) => {
      if (item.code === 'ADMINISTRATOR') {
        return (this.rootNode = { code: 0, name: '审计机构库', id: 0 })
      } else {
        const params = {
          orgId: userInfo.deptId,
        }
        axios({
          url: 'api/xcoa-mobile/v1/iamorg/getUserGroup',
          method: 'get',
        }).then((res) => {
          userInfo = res.data
          params.orgId = res.data.id
          axios({
            url: 'api/xcoa-mobile/v1/iamorg/findIamOrgId',
            method: 'post',
            params,
          }).then((res) => {
            this.id = res.data
            const deptCode = userInfo.id.toString()
            const deptName = userInfo.name
            return (this.rootNode = { code: deptCode, name: deptName, id: this.id })
          })
        })
      }
    })
  },
  mounted() {
    if (this.$route.query.record === undefined) {
      AuditWorkflowService.getFormNotIdList().then((res) => {
        const data1 = []
        const data2 = []
        const data3 = []
        res.forEach((item) => {
          if (item.nodePeriod === 'file-done') {
            data1.push(item)
          } else if (item.nodePeriod === 'profile') {
            data2.push(item)
          } else {
            data3.push(item)
          }
        })
        this.zbDate = data1
        this.ssDate = data2
        this.bgDate = data3
      })
    } else {
      const id = this.$route.query.record
      AuditWorkflowService.getFormList(id).then((res) => {
        const data1 = []
        const data2 = []
        const data3 = []
        res.forEach((item) => {
          if (item.nodePeriod === 'file-done') {
            data1.push(item)
          } else if (item.nodePeriod === 'profile') {
            data2.push(item)
          } else {
            data3.push(item)
          }
        })
        this.zbDate = data1
        this.ssDate = data2
        this.bgDate = data3
      })
    }
  },
  methods: {
    initparams(model) {
      axios({
        url: 'api/xcoa-mobile/v1/iamorg/getAccountGroup',
        method: 'get',
      }).then((res) => {
        if (res.data === true) {
          this.isfalse = false
        } else {
          this.isfalse = true
          if (model.id === undefined) {
            model.isDefault = '0'
          }
        }
      })
    },
    // 页面加载完成后
    sdFormReady() {
      const userInfo = getUserInfo()
      const creatorName = this.$refs.myForm.getFieldValue('creatorName')
      if (creatorName !== userInfo.name) {
        this.mode = 'VIEW'
        this.readOnly = true
      } else {
        this.mode = this.$refs.myForm.formData.mode
      }
    },
    ischange(model) {
      const value = this.$refs.myForm.getFieldValue('isDefault')
      if (value === '1') {
        this.$refs.myForm.setFieldValue('orgScopeMember', null)
        model.orgScopeMember = null
      }
    },
    validator(rule, value, callback) {
      value = encodeURIComponent(value)
      const id = this.$route.query.record || ''
      debounce(() => {
        axios.get(`api/xcoa-mobile/v1/iamworkflow/lc-name?lcName=${value}&id=` + id).then((res) => {
          if (res?.data === true) {
            callback()
          } else {
            callback('已存在，不允许重复')
          }
        })
      }, 500)()
    },
    close(flag) {
      crossWindowWatcher.notifyChange(this.$route.fullPath, flag)
      window.close()
    },
    saved() {
      this.close(true)
    },
    // 保存
    saveForm() {
      this.$refs.myForm.validateFields().then(() => {
        // 校验每一行都必填
        let sjdata = this.bgDate
        sjdata = sjdata.concat(this.ssDate)
        sjdata = sjdata.concat(this.zbDate)
        let flag = true
        sjdata.forEach((item) => {
          if (item.nodeStatus === undefined) {
            flag = false
          }
        })
        if (flag) {
          var data = this.$refs.myForm.getBackendValues()
          const nodeDate = this.zbDate.concat(this.ssDate).concat(this.bgDate)
          const d = []
          d.push({ data: data })
          d.push({ datalist: nodeDate })
          AuditWorkflowService.saveNodeList(d).then((res) => {
            this.close(true)
          })
        } else {
          Modal.warning({
            title: '提示',
            content: '请完善每个阶段设置!',
          })
          return false
        }
      })
      // this.$refs.myForm.saveBtnClick()
    },
    onclickchange(str, v) {
      if (this.mode !== 'VIEW') {
        v.nodeStatus = str
        this.$forceUpdate()
      }
    },
  },
}
</script>

<style module lang="scss">
@import '@/webflow/sd-flow-form.scss';
.item2 {
  width: 90%;
  padding: 8px;
  margin: 0 auto;
  border: 1px solid #eee;
  .head {
    padding: 0.5rem 0;
    background-color: rgb(243, 243, 202);
    // opacity: 0.2;
    border: 1px solid orange;
  }
  .body > div {
    display: flex;
    flex-direction: row;
    align-items: center;
    justify-content: space-between;
    padding: 0.5rem 0;

    button {
      margin: 0 0.25rem;
    }
  }
}
</style>
