<template>
    <div class="custom-table">
        <div class="tool">
            <el-button type="primary" icon="el-icon-plus" @click="handleAddResource">新增</el-button>
        </div>
        <el-table
                :data="list"
                border
                v-loading="loading">
            <el-table-column type="index" align="center" label="序号" width="80"/>
            <el-table-column prop="code" label="编号/ID" show-overflow-tooltip align="center"/>
            <el-table-column prop="enforce_obj_name" show-overflow-tooltip label="单位名称"/>
            <el-table-column prop="enforce_obj_name" show-overflow-tooltip label="场所类型">
                <template slot-scope="scope">
                    {{ getPlaceTypeName(scope.row.place_type) }}
                </template>
            </el-table-column>
            <el-table-column prop="unitSize" show-overflow-tooltip label="单位规模"/>
            <el-table-column prop="legal_person" label="单位法人" show-overflow-tooltip align="center"/>
            <el-table-column prop="legal_person_phone" label="联系方式" align="center" width="120"/>
            <el-table-column prop="enforce_org_name" label="所属辖区" show-overflow-tooltip align="center"/>
            <el-table-column prop="enforce_obj_address" label="单位地址" show-overflow-tooltip/>
            <el-table-column prop="status" label="近期检查" align="center" show-overflow-tooltip/>
            <el-table-column prop="manage_status" label="经营状态" align="center">
              <template slot-scope="scope">
                <el-tooltip class="item" effect="dark" :content="scope.row.blocked_begin_time_text" placement="top" v-if="scope.row.manage_status == '冻结' && scope.row.blocked_begin_time_text">
                  <span>{{ scope.row.manage_status }}</span>
                </el-tooltip>
                <span v-else>{{scope.row.manage_status}}</span>
              </template>
            </el-table-column>
            <el-table-column prop="action" label="操作" align="center" width="270">
                <template slot-scope="scope">
                  <template v-if="scope.row.manage_status === '注销'">
                    <el-button type="text" size="small" @click="handleDetail(scope.row.id)">查看</el-button>
                  </template>
                  <template v-else>
                    <el-button type="text" size="small" @click="handleTag(scope.row.id)">标签</el-button>
                    <el-button type="text" size="small" @click="handleDetail(scope.row.id)">查看</el-button>
                    <el-button type="text" size="small" @click="configProcess(scope.row.id)">配置流程</el-button>
                    <el-button type="text" size="small" @click="handleEdit(scope.row.id)">编辑</el-button>
                    <el-button class="handle-btn" type="text" size="small" @click="handleFrozen(scope.row, 1)" v-if="scope.row.manage_status === '正常'">冻结</el-button>
                    <el-button class="handle-btn" type="text" size="small" @click="handleFrozen(scope.row, 0)" v-else-if="scope.row.manage_status === '冻结'">解冻</el-button>
                    <el-button type="text" size="small" @click="handleFrozen(scope.row, 2)">注销</el-button>
                  </template>
                </template>
            </el-table-column>
        </el-table>
        <div class="custom-pagination">
            <div class="info">
                <span>共 {{ total }} 条记录</span>
                <span>第 {{ query.page }} / {{ pageTotal }} 页</span>
            </div>
            <el-pagination
                    background
                    class="custom-page"
                    layout="prev, pager, next, sizes"
                    :page-sizes="[10, 20, 50, 100]"
                    :current-page="query.page"
                    :page-size="query.size"
                    :total="total"
                    @size-change="handleSizeChange"
                    @current-change="handleCurrentChange">
            </el-pagination>
        </div>
        <el-dialog title="选择流程" :visible.sync="showTemplate" v-if="showTemplate">
            <choose-template-v2 @changeTemplate="handleTemplate" :place_type="place_type"
                                :enforce_obj_type="enforce_obj_type">
            </choose-template-v2>
        </el-dialog>
        <el-dialog title="设置标签" :visible.sync="showTagDialog" v-if="showTagDialog">
            <tag-setting :obj_id="objId" @hide="hideTagDialog"></tag-setting>
        </el-dialog>
      <el-dialog
        :title="manageTitle"
        :visible.sync="showFrozenDialog"
        width="542px"
        >
        <div class="frozen-dialog">
          <div class="frozen-item" v-if="manageType === 1">
            <span class="item-title"><i>*</i>冻结原因：</span>
            <el-select v-model="frozenValue" placeholder="请选择冻结原因">
              <el-option
                v-for="(item, i) in frozenOptions"
                :key="i"
                :label="item.label"
                :value="item.value">
              </el-option>
            </el-select>
          </div>
          <div class="frozen-item" v-if="manageType === 1">
            <span class="item-title"><i>*</i>冻结时间：</span>
            <el-date-picker
              ref="date-picker"
              class="frozen-time"
              v-model="frozenTime"
              type="datetime"
              default-time="00:00:00"
              :picker-options="pickerOptions"
              @blur="blurTime"
              placeholder="选择日期时间">
            </el-date-picker>
            <p class="frozen-time-tip">*超过此日期自动解冻</p>
          </div>
          <div class="frozen-item frozen-desc" :class="{'frozen-desc1': manageType===2}">
            <span class="item-title"><i>*</i>{{manageType === 0 ? '解冻原因' : manageType === 1 ? '详细描述' : '注销原因'}}：</span>
            <el-input
              type="textarea"
              resize="none"
              :rows="6"
              show-word-limit
              maxlength="300"
              placeholder="请输入内容"
              v-model="status_reason">
            </el-input>
            <p class="frozen-time-tip" v-if="manageType === 2">*注销单位后不可恢复，请谨慎操作。</p>
          </div>
        </div>
        <span slot="footer" class="dialog-footer">
          <el-button @click="showFrozenDialog = false">取 消</el-button>
          <el-button type="primary" @click="confirmModel">确 定</el-button>
        </span>
      </el-dialog>
    </div>
</template>

<script>
    import {getEnforceList, removeEnforce, updateEnforce, getEnforceItem} from '@/api/resource'
    import {getPlaceTypes} from '@/api/resource'
    import {resourceMixin} from '@/mixin/resource'
    import ChooseTemplateV2 from '@/component/ChooseTemplateV2.vue'
    import TagSetting from './TagSetting.vue'
    import moment from 'moment'

    export default {
        computed: {
            pageTotal() {
                const page = Math.ceil(this.total / this.query.size)
                return page > 0 ? page : 1
            }
        },
        components: {
            ChooseTemplateV2,
            TagSetting,
        },

        mixins: [resourceMixin],
        data() {
            return {
                query: {
                    page: 1,
                    size: 10,
                    query: null,
                    tag_id: null,
                    // query=enforce_obj_name==重庆东田实业有限公司;legal_person==法人
                },

                formData: {
                    enforce_obj_name: '',
                    legal_person: '',
                    unitSize: '',
                    enforce_org_id: '',
                    safe: '',
                    check: '',
                },
                showTemplate: false,
                loading: false,
                list: [],
                placeTypeList: [],
                total: 0,
                objId: -1,
                objData: {},
                place_type: '',
                enforce_obj_type: '',
                showTagDialog: false,
                showFrozenDialog: false,
              frozenOptions: [{
                value: '暂停营业',
                label: '暂停营业'
              }, {
                value: '搬迁',
                label: '搬迁'
              }, {
                value: '其他',
                label: '其他'
              }],
              frozenValue: '',
              frozenTime: '',
              status_reason: '',
              currentId: '',
              manage_status: '',
              manageType: '',
              manageTitle: '',
              paramsData: '',
              pickerOptions: {
                disabledDate(time) {
                  return time.getTime() < Date.now();
                },
                // selectableRange: `${(new Date()).getHours()}:${(new Date()).getMinutes()}:${(new Date()).getSeconds()}-24:00:00`
              }
            }
        },
        mounted() {
            this.getPlaceTypesAll();
            this.handleQuery()
        },
        methods: {
          blurTime(val) {
            this.frozenTime = val.displayValue ? new Date(val.displayValue) : ''
            if (new Date(val.displayValue) < new Date().getTime()) {
              this.$message.error('冻结时间需要大于当前时间');
              this.$refs['date-picker'].focus()
              return
            }
          },
          confirmModel() {
            let params = {
              manage_status: 1,
              change_detail: this.frozenValue,
              change_resonse: this.status_reason,
              blocked_end_time: this.frozenTime
            }
            if (this.manageType === 1) {
              if (!this.frozenValue) {
                this.$message.error('请选择冻结原因');
                return
              }
              if (!this.frozenTime) {
                this.$message.error('请选择冻结时间');
                return
              }
              if (!this.status_reason) {
                this.$message.error('请输入详细描述');
                return
              }
            } else if (this.manageType === 2) {
              if (!this.status_reason) {
                this.$message.error('请输入注销原因');
                return
              }
              params.manage_status = 2
              params.change_detail = ''
              params.blocked_end_time = ''
            } else if (this.manageType === 0) {
              if (!this.status_reason) {
                this.$message.error('请输入解冻原因');
                return
              }
              params.manage_status = 0
              params.change_detail = ''
              params.blocked_end_time = ''
            }
            params = {...this.paramsData, ...params}
            updateEnforce(this.currentId, params).then(res => {
              this.$message.success('操作成功');
              this.showFrozenDialog = false
              this.handleQuery()
            }).catch(e => {
              this.$message.error('操作失败，请重试！');
            })
          },
            // 冻结操作
            handleFrozen(row, type) {
              this.paramsData = row
              this.manageType = type
              this.manageTitle = type === 0 ? '解冻单位' : type === 1 ? '冻结单位' : '注销单位'
              this.currentId = row.id
              const manage_status = this.operateStatus.find(it => it.name === row.manage_status)
              if (manage_status) this.manage_status = manage_status.id
              this.frozenValue = ''
              this.status_reason = ''
              this.frozenTime = ''
              this.showFrozenDialog = true
            },
            async getPlaceTypesAll() {
                const list = await getPlaceTypes();
                if (list && list.length > 0) {
                    this.placeTypeList = list;
                }
            },
            configProcess(objId) {
                this.objId = objId;
                getEnforceItem(this.objId).then((res) => {
                    this.objData = res;
                    this.enforce_obj_type = this.objData.enforce_obj_type
                    this.place_type = this.objData.place_type
                    this.showTemplate = true;
                });
                // this.showTemplate=true;
            },
            handleTemplate(data) {
                // let result ={
                //     enforce_template_id:data.id,
                //     enforce_template_name:data.template_name
                // };
                this.objData.enforce_template_id = data.id;
                this.objData.enforce_template_name = data.template_name;
                updateEnforce(this.objId, this.objData).then(() => {
                    this.$message.success('修改成功')
                    this.showTemplate = false;
                }).catch(reason => {
                    this.$message.error('修改失败')
                    this.showTemplate = false;
                })
            },
            getPlaceTypeName(placeType) {
                let name = "";
                this.placeTypeList.forEach(item => {
                    if (item.code === placeType) {
                        name = item.name;
                    }
                });
                return name;
            },
            resetForm(data, tag_id) {
                this.query.query = data
                this.query.page = 1
                this.query.size = 10
                this.query.tag_id = tag_id
                this.handleQuery()
            },
            handleSizeChange(val) {
                this.query.size = val
                this.handleQuery()
            },
            handleCurrentChange(val) {
                this.query.page = val
                this.handleQuery()
            },
            handleQueryParam() {
                const res = []
                Object.keys(this.formData).forEach(key => {
                    if (this.formData[key]) {
                        res.push(`${key}==${this.formData[key]}`)
                    }
                })
                this.query.query = res.join(';')
            },
            handleQuery() {
                this.loading = true
                const vm = this
                getEnforceList(this.query).then(res => {
                    if (res) {
                        vm.total = res.total || 0
                        const list = res.data || []
                        list.map(item => {
                            item.unitSize = vm.parseUnitSize(item.enforce_obj_type)
                            item.status = vm.parseStatus(item.last_enforce_status)
                            item.manage_status = this.manageStatus[item.manage_status] || ''
                            item.blocked_begin_time_text = item.blocked_end_time ? '冻结时间：' + moment(item.blocked_end_time).format("YYYY-MM-DD HH:mm:ss") : ''
                        })
                        vm.list = list
                    }
                    vm.loading = false
                })
            },
            handleDetail(id) {
                this.$router.push({
                    path: '/resource/detail',
                    query: {
                        id
                    }
                })
            },
            handleTag(id) {
                this.objId = id
                this.showTagDialog = true
            },
            handleAddResource() {
                this.$router.push('/resource/add')
            },
            handleEdit(id) {
                this.$router.push({
                    path: '/resource/edit',
                    query: {
                        id
                    }
                })
            },
            handleDelete(data) {
                this.$confirm(`是否删除执法对象 ${data.enforce_obj_name}?`, '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    removeEnforce(data.id).then(res => {
                        this.$message({
                            type: 'success',
                            message: '删除成功!'
                        })
                        this.handleCurrentChange(1)
                    })
                })
            },
            hideTagDialog() {
                this.showTagDialog = false
            }
        }
    }
</script>
<style lang="scss" scoped>
.custom-table {
  .frozen-dialog {
    padding: 0 30px;
    .frozen-item {
      margin-bottom: 10px;
      &.frozen-desc {
        display: flex;
        position: relative;
        .item-title {
          min-width: 84px;
        }
        .frozen-time-tip {
          position: absolute;
          bottom: -30px;
        }
      }
      .item-title {
        display: inline-block;
        min-width: 84px;
        i {
          color: red;
          padding-right: 2px;
          font-style: normal;
        }
      }
      /deep/.el-select--medium {
        width: 357px;
      }
      /deep/.frozen-time {
        width: 357px;
      }
      .frozen-time-tip {
        color: red;
        padding: 5px 0 0 76px;
        margin: 0;
      }
    }
  }
}
</style>
